A guide to Refactoring mock clones in spring-security
Mock Clone Instance #spring-security_MCI_1
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterRegistration.Dynamic
- Test Case Count: 15
- MO Count: 15
Reusable Method
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
The refactoring details in each test cases
Test Case ID #spring-security_Test_1_1
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- verify(registration).setAsyncSupported(true);
+ verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_2
Test Case Name: onStartupWhenConfigurationClassThenAddsContextLoaderListener(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
@@
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- verify(registration).setAsyncSupported(true);
+ verify(registration).setAsyncSupported(true);
verify(context).addListener(any(ContextLoaderListener.class));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(any(ContextLoaderListener.class));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_3
Test Case Name: onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- verify(registration).setAsyncSupported(true);
+ verify(registration).setAsyncSupported(true);
verify(context).addListener(HttpSessionEventPublisher.class.getName());
}
Original Test Code (click to expand)
@Test
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(HttpSessionEventPublisher.class.getName());
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_4
Test Case Name: onStartupWhenCustomSecurityDispatcherTypesThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenCustomSecurityDispatcherTypesThenUses() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
+ verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
- verify(registration).setAsyncSupported(true);
+ verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenCustomSecurityDispatcherTypesThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_5
Test Case Name: onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected String getDispatcherWebApplicationContextSuffix() {
return "dispatcher";
}
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute()).isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- verify(registration).setAsyncSupported(true);
+ verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected String getDispatcherWebApplicationContextSuffix() {
return "dispatcher";
}
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute()).isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_6
Test Case Name: onStartupWhenInsertFiltersThenInserted(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenInsertFiltersThenInserted() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- verify(registration, times(3)).setAsyncSupported(true);
+ verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context).addFilter(anyString(), eq(filter1));
verify(context).addFilter(anyString(), eq(filter2));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenInsertFiltersThenInserted() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context).addFilter(anyString(), eq(filter1));
verify(context).addFilter(anyString(), eq(filter2));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_7
Test Case Name: onStartupWhenDuplicateFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenDuplicateFilterInsertedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterInsertedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_8
Test Case Name: onStartupWhenInsertFiltersEmptyThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenInsertFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Original Test Code (click to expand)
@Test
public void onStartupWhenInsertFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_9
Test Case Name: onStartupWhenNullFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenNullFilterInsertedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterInsertedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_10
Test Case Name: onStartupWhenAppendFiltersThenAppended(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenAppendFiltersThenAppended() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context, times(3)).addFilter(anyString(), any(Filter.class));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenAppendFiltersThenAppended() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context, times(3)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_11
Test Case Name: onStartupWhenDuplicateFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenDuplicateFilterAppendedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
- verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterAppendedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_12
Test Case Name: onStartupWhenAppendFiltersEmptyThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenAppendFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Original Test Code (click to expand)
@Test
public void onStartupWhenAppendFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_13
Test Case Name: onStartupWhenNullFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenNullFilterAppendedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterAppendedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_14
Test Case Name: onStartupWhenDefaultsThenSessionTrackingModes(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenDefaultsThenSessionTrackingModes() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenDefaultsThenSessionTrackingModes() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Test Case ID #spring-security_Test_1_15
Test Case Name: onStartupWhenSessionTrackingModesConfiguredThenUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: registration
Suggested Diff
@@
@Test
public void onStartupWhenSessionTrackingModesConfiguredThenUsed() {
ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ // removed local mock; replaced with global field `registration`
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
willDoNothing().given(context).setSessionTrackingModes(any());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenSessionTrackingModesConfiguredThenUsed() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
willDoNothing().given(context).setSessionTrackingModes(any());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);
}
Reusable Method for MCI (click to expand)
private FilterRegistration.Dynamic registration;
@BeforeEach
public void setUp() {
registration = mock(FilterRegistration.Dynamic.class);
}
registration;
Mock Clone Instance #spring-security_MCI_2
- Scope: method level
- Mocked Class:
java.util.function.Supplier<org.springframework.security.oauth2.jwt.ReactiveJwtDecoder>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Supplier<ReactiveJwtDecoder> createMockBrokenSupplier() {
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_2_1
Test Case Name: decodeWhenInitializationFailsThenInitializationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierReactiveJwtDecoderTests.java)
Mock Object Variable Name: broken
Suggested Diff
@@
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
- Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
- given(broken.get()).willThrow(RuntimeException.class);
+ Supplier<ReactiveJwtDecoder> broken = createMockBrokenSupplier();
ReactiveJwtDecoder jwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> jwtDecoder.decode("token").block());
verify(broken).get();
}
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
ReactiveJwtDecoder jwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> jwtDecoder.decode("token").block());
verify(broken).get();
}
Reusable Method for MCI (click to expand)
private static Supplier<ReactiveJwtDecoder> createMockBrokenSupplier() {
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
Test Case ID #spring-security_Test_2_2
Test Case Name: decodeWhenInitializationInitiallyFailsThenRecoverable(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierReactiveJwtDecoderTests.java)
Mock Object Variable Name: broken
Suggested Diff
@@
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
- Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
- given(broken.get()).willThrow(RuntimeException.class);
+ Supplier<ReactiveJwtDecoder> broken = createMockBrokenSupplier();
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierReactiveJwtDecoder.decode("token").block());
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
@@
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierReactiveJwtDecoder.decode("token").block());
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private static Supplier<ReactiveJwtDecoder> createMockBrokenSupplier() {
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
Mock Clone Instance #spring-security_MCI_3
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.AuthorizationManager<org.springframework.security.authorization.method.MethodInvocationResult>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthorizationManager<MethodInvocationResult> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_3_1
Test Case Name: beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterMethodInterceptorTests.java)
Mock Object Variable Name: mockAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(result.getResult());
- AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
- given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = createMockAuthorizationManager();
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
Object returnedObject = advice.invoke(mockMethodInvocation);
assertThat(returnedObject).isEqualTo(result.getResult());
verify(mockAuthorizationManager).check(any(Supplier.class), any(MethodInvocationResult.class));
@@
Original Test Code (click to expand)
@Test
public void beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject() throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
given(mockMethodInvocation.proceed()).willReturn(result.getResult());
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
Object returnedObject = advice.invoke(mockMethodInvocation);
assertThat(returnedObject).isEqualTo(result.getResult());
verify(mockAuthorizationManager).check(any(Supplier.class), any(MethodInvocationResult.class));
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<MethodInvocationResult> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Test Case ID #spring-security_Test_3_2
Test Case Name: invokeWhenCustomAuthorizationDeniedExceptionThenThrows(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterMethodInterceptorTests.java)
Mock Object Variable Name: manager
Suggested Diff
@@
given(mi.proceed()).willReturn("ok");
- AuthorizationManager<MethodInvocationResult> manager = mock(AuthorizationManager.class);
- given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
- given(manager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<MethodInvocationResult> manager = createMockAuthorizationManager();
+ given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(mi));
@@
Original Test Code (click to expand)
@Test
public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() throws Throwable {
MethodInvocation mi = mock(MethodInvocation.class);
given(mi.proceed()).willReturn("ok");
AuthorizationManager<MethodInvocationResult> manager = mock(AuthorizationManager.class);
given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
given(manager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(mi));
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<MethodInvocationResult> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_4
- Scope: class level
- Mocked Class:
org.springframework.web.server.WebFilter
- Test Case Count: 2
- MO Count: 2
Reusable Method
public class MockWebFilter {
public static org.springframework.web.server.WebFilter createMockWebFilter(reactor.core.publisher.Mono<?> monoReturn) {
org.springframework.web.server.WebFilter mock = mock(org.springframework.web.server.WebFilter.class);
given(mock.filter(any(), any())).willReturn(monoReturn);
return mock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_4_1
Test Case Name: decorateWhenCustomAfterFilterThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: mock
Suggested Diff
@@
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilter mock = mock(WebFilter.class);
- given(mock.filter(any(), any())).willReturn(Mono.empty());
+ WebFilter mock = MockWebFilter.createMockWebFilter(Mono.empty());
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of((e, c) -> c.filter(e).then(Mono.deferContextual((context) -> {
Observation parentObservation = context.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted("custom", registry).parentObservation(parentObservation).contextualName("custom").start();
return Mono.just("3").doOnSuccess((v) -> observation.stop()).doOnCancel(observation::stop).doOnError((t) -> {
observation.error(t);
observation.stop();
}).then(Mono.empty());
}))));
@@
Original Test Code (click to expand)
@Test
void decorateWhenCustomAfterFilterThenObserves() {
AccumulatingObservationHandler handler = new AccumulatingObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilter mock = mock(WebFilter.class);
given(mock.filter(any(), any())).willReturn(Mono.empty());
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of((e, c) -> c.filter(e).then(Mono.deferContextual((context) -> {
Observation parentObservation = context.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted("custom", registry).parentObservation(parentObservation).contextualName("custom").start();
return Mono.just("3").doOnSuccess((v) -> observation.stop()).doOnCancel(observation::stop).doOnError((t) -> {
observation.error(t);
observation.stop();
}).then(Mono.empty());
}))));
Observation http = Observation.start("http", registry).contextualName("http");
try {
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, http)).block();
} finally {
http.stop();
}
handler.assertSpanStart(0, "http", null);
handler.assertSpanStart(1, "spring.security.filterchains", "http");
handler.assertSpanStop(2, "security filterchain before");
handler.assertSpanStart(3, "secured request", "security filterchain before");
handler.assertSpanStop(4, "secured request");
handler.assertSpanStart(5, "spring.security.filterchains", "http");
handler.assertSpanStart(6, "custom", "spring.security.filterchains");
handler.assertSpanStop(7, "custom");
handler.assertSpanStop(8, "security filterchain after");
handler.assertSpanStop(9, "http");
}
Reusable Method for MCI (click to expand)
public class MockWebFilter {
public static org.springframework.web.server.WebFilter createMockWebFilter(reactor.core.publisher.Mono<?> monoReturn) {
org.springframework.web.server.WebFilter mock = mock(org.springframework.web.server.WebFilter.class);
given(mock.filter(any(), any())).willReturn(monoReturn);
return mock;
}
}
Test Case ID #spring-security_Test_4_2
Test Case Name: doFilterWhenFilterExceptionThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: error
Suggested Diff
@@
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
- WebFilter error = mock(WebFilter.class);
- given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException()));
+ WebFilter error = MockWebFilter.createMockWebFilter(Mono.error(new IllegalStateException()));
List<WebFilter> filters = Arrays.asList(error);
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
WebFilter error = mock(WebFilter.class);
given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException()));
List<WebFilter> filters = Arrays.asList(error);
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block());
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Reusable Method for MCI (click to expand)
public class MockWebFilter {
public static org.springframework.web.server.WebFilter createMockWebFilter(reactor.core.publisher.Mono<?> monoReturn) {
org.springframework.web.server.WebFilter mock = mock(org.springframework.web.server.WebFilter.class);
given(mock.filter(any(), any())).willReturn(monoReturn);
return mock;
}
}
Mock Clone Instance #spring-security_MCI_5
- Scope: class level
- Mocked Class:
org.springframework.web.reactive.function.BodyExtractor<reactor.core.publisher.Mono<org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse>, org.springframework.http.ReactiveHttpInputMessage>
- Test Case Count: 2
- MO Count: 5
Reusable Method
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_5_1
Test Case Name: getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveAuthorizationCodeTokenResponseClientTests.java)
Suggested Diff
@@
WebClientReactiveAuthorizationCodeTokenResponseClient customClient = new WebClientReactiveAuthorizationCodeTokenResponseClient();
- BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
- given(extractor.extract(any(), any())).willReturn(Mono.just(response));
+ BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = MockBodyExtractor.createMockBodyExtractor(response);
customClient.setBodyExtractor(extractor);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(authorizationCodeGrantRequest()).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
WebClientReactiveAuthorizationCodeTokenResponseClient customClient = new WebClientReactiveAuthorizationCodeTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(authorizationCodeGrantRequest()).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
Test Case ID #spring-security_Test_5_2
Test Case Name: getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveClientCredentialsTokenResponseClientTests.java)
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
WebClientReactiveClientCredentialsTokenResponseClient customClient = new WebClientReactiveClientCredentialsTokenResponseClient();
- BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
- given(extractor.extract(any(), any())).willReturn(Mono.just(response));
+ BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = MockBodyExtractor.createMockBodyExtractor(response);
customClient.setBodyExtractor(extractor);
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(request).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
this.server.enqueue(MockResponses.json("access-token-response.json"));
WebClientReactiveClientCredentialsTokenResponseClient customClient = new WebClientReactiveClientCredentialsTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(request).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
Test Case ID #spring-security_Test_5_3
Test Case Name: getTokenResponseWhenBodyExtractorSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: bodyExtractor
Suggested Diff
@@
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
- given(bodyExtractor.extract(any(), any())).willReturn(Mono.just(response));
+ BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = MockBodyExtractor.createMockBodyExtractor(response);
ClientRegistration clientRegistration = this.clientRegistration.build();
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenBodyExtractorSetThenCalled() {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(bodyExtractor.extract(any(), any())).willReturn(Mono.just(response));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
this.client.setBodyExtractor(bodyExtractor);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(bodyExtractor).extract(any(), any());
}
Reusable Method for MCI (click to expand)
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
Test Case ID #spring-security_Test_5_4
Test Case Name: getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactivePasswordTokenResponseClientTests.java)
Suggested Diff
@@
WebClientReactivePasswordTokenResponseClient customClient = new WebClientReactivePasswordTokenResponseClient();
- BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
- given(extractor.extract(any(), any())).willReturn(Mono.just(response));
+ BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = MockBodyExtractor.createMockBodyExtractor(response);
customClient.setBodyExtractor(extractor);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(passwordGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
WebClientReactivePasswordTokenResponseClient customClient = new WebClientReactivePasswordTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(clientRegistration, this.username, this.password);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(passwordGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
Test Case ID #spring-security_Test_5_5
Test Case Name: getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveRefreshTokenTokenResponseClientTests.java)
Suggested Diff
@@
WebClientReactiveRefreshTokenTokenResponseClient customClient = new WebClientReactiveRefreshTokenTokenResponseClient();
- BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
- given(extractor.extract(any(), any())).willReturn(Mono.just(response));
+ BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = MockBodyExtractor.createMockBodyExtractor(response);
customClient.setBodyExtractor(extractor);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(refreshTokenGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenSuccessCustomResponseThenReturnAccessTokenResponse() {
WebClientReactiveRefreshTokenTokenResponseClient customClient = new WebClientReactiveRefreshTokenTokenResponseClient();
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
OAuth2AccessTokenResponse response = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
customClient.setBodyExtractor(extractor);
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2AccessTokenResponse accessTokenResponse = customClient.getTokenResponse(refreshTokenGrantRequest).block();
assertThat(accessTokenResponse.getAccessToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockBodyExtractor {
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> createMockBodyExtractor(OAuth2AccessTokenResponse response) {
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> extractor = mock();
given(extractor.extract(any(), any())).willReturn(Mono.just(response));
return extractor;
}
}
Mock Clone Instance #spring-security_MCI_6
- Scope: method level
- Mocked Class:
org.springframework.context.ApplicationEventPublisher
- Test Case Count: 6
- MO Count: 6
Reusable Method
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
The refactoring details in each test cases
Test Case ID #spring-security_Test_6_1
Test Case Name: expectedDefaultMappingsAreSatisfied(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
@Test
public void expectedDefaultMappingsAreSatisfied() {
this.publisher = new DefaultAuthenticationEventPublisher();
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
Authentication a = mock(Authentication.class);
Exception cause = new Exception();
Object extraInfo = new Object();
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
this.publisher.publishAuthenticationFailure(new LockedException(""), a);
this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
verifyNoMoreInteractions(appPublisher);
}
Original Test Code (click to expand)
@Test
public void expectedDefaultMappingsAreSatisfied() {
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
Authentication a = mock(Authentication.class);
Exception cause = new Exception();
Object extraInfo = new Object();
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
this.publisher.publishAuthenticationFailure(new LockedException(""), a);
this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
verifyNoMoreInteractions(appPublisher);
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Test Case ID #spring-security_Test_6_2
Test Case Name: authenticationSuccessIsPublished(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
@Test
public void authenticationSuccessIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
- verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
+ verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
this.publisher.setApplicationEventPublisher(null);
// Should be ignored with null app publisher
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
}
Original Test Code (click to expand)
@Test
public void authenticationSuccessIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
this.publisher.setApplicationEventPublisher(null);
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Test Case ID #spring-security_Test_6_3
Test Case Name: additionalExceptionMappingsAreSupported(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
@Test
public void additionalExceptionMappingsAreSupported() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
Original Test Code (click to expand)
@Test
public void additionalExceptionMappingsAreSupported() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Test Case ID #spring-security_Test_6_4
Test Case Name: unknownFailureExceptionIsIgnored(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
@Test
public void unknownFailureExceptionIsIgnored() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verifyNoMoreInteractions(appPublisher);
}
Original Test Code (click to expand)
@Test
public void unknownFailureExceptionIsIgnored() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verifyNoMoreInteractions(appPublisher);
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Test Case ID #spring-security_Test_6_5
Test Case Name: additionalExceptionMappingsUsingMapAreSupported(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
this.publisher.setAdditionalExceptionMappings(mappings);
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
- verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
+ verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
Original Test Code (click to expand)
@Test
public void additionalExceptionMappingsUsingMapAreSupported() {
this.publisher = new DefaultAuthenticationEventPublisher();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(MockAuthenticationException.class, AuthenticationFailureDisabledEvent.class);
this.publisher.setAdditionalExceptionMappings(mappings);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"), mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Test Case ID #spring-security_Test_6_6
Test Case Name: defaultAuthenticationFailureEventIsPublished(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DefaultAuthenticationEventPublisherTests.java)
Mock Object Variable Name: appPublisher
Suggested Diff
@@
@Test
public void defaultAuthenticationFailureEventIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
- ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
+ // removed local mock; replaced with global field `appPublisher`
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
- verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
+ verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
Original Test Code (click to expand)
@Test
public void defaultAuthenticationFailureEventIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
Reusable Method for MCI (click to expand)
private ApplicationEventPublisher appPublisher;
@BeforeEach
public void setUp() {
appPublisher = mock(ApplicationEventPublisher.class);
}
appPublisher
Mock Clone Instance #spring-security_MCI_7
- Scope: method level
- Mocked Class:
io.micrometer.observation.ObservationHandler<?>
- Test Case Count: 5
- MO Count: 5
Reusable Method
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_7_1
Test Case Name: decorateWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateWhenDefaultsThenObserves() throws Exception {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler).onStart(any());
}
Original Test Code (click to expand)
@Test
void decorateWhenDefaultsThenObserves() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler).onStart(any());
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Test Case ID #spring-security_Test_7_2
Test Case Name: decorateWhenNoopThenDoesNotObserve(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
void decorateWhenNoopThenDoesNotObserve() throws Exception {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verifyNoInteractions(handler);
}
@@
Original Test Code (click to expand)
@Test
void decorateWhenNoopThenDoesNotObserve() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verifyNoInteractions(handler);
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Test Case ID #spring-security_Test_7_3
Test Case Name: decorateFiltersWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateFiltersWhenDefaultsThenObserves() throws Exception {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler, times(2)).onStart(any());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo(filter.getClass().getSimpleName() + ".before");
assertThat(events.get(1).getName()).isEqualTo(filter.getClass().getSimpleName() + ".after");
}
Original Test Code (click to expand)
@Test
void decorateFiltersWhenDefaultsThenObserves() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler, times(2)).onStart(any());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo(filter.getClass().getSimpleName() + ".before");
assertThat(events.get(1).getName()).isEqualTo(filter.getClass().getSimpleName() + ".after");
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Test Case ID #spring-security_Test_7_4
Test Case Name: decorateFiltersWhenDefaultsThenUsesEventName(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateFiltersWhenDefaultsThenUsesEventName() throws Exception {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = new BasicAuthenticationFilter();
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo("authentication.basic.before");
assertThat(events.get(1).getName()).isEqualTo("authentication.basic.after");
}
Original Test Code (click to expand)
@Test
void decorateFiltersWhenDefaultsThenUsesEventName() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = new BasicAuthenticationFilter();
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo("authentication.basic.before");
assertThat(events.get(1).getName()).isEqualTo("authentication.basic.after");
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Test Case ID #spring-security_Test_7_5
Test Case Name: decorateFiltersWhenErrorsThenClosesObservationOnlyOnce(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateFiltersWhenErrorsThenClosesObservationOnlyOnce() throws Exception {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
willThrow(IllegalArgumentException.class).given(filter).doFilter(any(), any(), any());
FilterChain decorated = decorator.decorate(chain, List.of(filter));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse()));
verify(handler).onScopeClosed(any());
}
Original Test Code (click to expand)
@Test
void decorateFiltersWhenErrorsThenClosesObservationOnlyOnce() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
willThrow(IllegalArgumentException.class).given(filter).doFilter(any(), any(), any());
FilterChain decorated = decorator.decorate(chain, List.of(filter));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse()));
verify(handler).onScopeClosed(any());
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Mock Clone Instance #spring-security_MCI_8
- Scope: method level
- Mocked Class:
io.micrometer.observation.ObservationHandler<?>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_8_1
Test Case Name: decorateWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
void decorateWhenDefaultsThenObserves() {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verify(handler).onStart(any());
}
@@
Original Test Code (click to expand)
@Test
void decorateWhenDefaultsThenObserves() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verify(handler).onStart(any());
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Test Case ID #spring-security_Test_8_2
Test Case Name: decorateWhenNoopThenDoesNotObserve(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateWhenNoopThenDoesNotObserve() {
- ObservationHandler<?> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<?> handler = createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verifyNoInteractions(handler);
}
Original Test Code (click to expand)
@Test
void decorateWhenNoopThenDoesNotObserve() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verifyNoInteractions(handler);
}
Reusable Method for MCI (click to expand)
private static ObservationHandler<?> createMockObservationHandler() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
Mock Clone Instance #spring-security_MCI_9
- Scope: method level
- Mocked Class:
org.springframework.test.context.TestContext
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static TestContext createMockTestContext(Method testMethod) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(testMethod);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
return testContext;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_9_1
Test Case Name: handlesGenericAnnotation(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\context\support\WithSecurityContextTestExcecutionListenerTests.java)
Mock Object Variable Name: testContext
Suggested Diff
@@
Method method = ReflectionUtils.findMethod(WithSecurityContextTestExcecutionListenerTests.class, "handlesGenericAnnotationTestMethod");
- TestContext testContext = mock(TestContext.class);
- given(testContext.getTestMethod()).willReturn(method);
- given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
+ TestContext testContext = createMockTestContext(method);
this.listener.beforeTestMethod(testContext);
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).isInstanceOf(WithSuperClassWithSecurityContext.class);
}
Original Test Code (click to expand)
@Test
public
void handlesGenericAnnotation() throws Exception {
Method method = ReflectionUtils.findMethod(WithSecurityContextTestExcecutionListenerTests.class, "handlesGenericAnnotationTestMethod");
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(method);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(testContext);
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal()).isInstanceOf(WithSuperClassWithSecurityContext.class);
}
Reusable Method for MCI (click to expand)
private static TestContext createMockTestContext(Method testMethod) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(testMethod);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
return testContext;
}
Test Case ID #spring-security_Test_9_2
Test Case Name: beforeTestMethodNoApplicationContext(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\context\support\WithSecurityContextTestExcecutionListenerTests.java)
Mock Object Variable Name: testContext
Suggested Diff
@@
Class testClass = FakeTest.class;
- given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException());
- given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testWithMockUser"));
+ this.testContext = createMockTestContext(ReflectionUtils.findMethod(testClass, "testWithMockUser"));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
Original Test Code (click to expand)
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodNoApplicationContext() throws Exception {
Class testClass = FakeTest.class;
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException());
given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testWithMockUser"));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
Reusable Method for MCI (click to expand)
private static TestContext createMockTestContext(Method testMethod) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(testMethod);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
return testContext;
}
Test Case ID #spring-security_Test_9_3
Test Case Name: beforeTestMethodInnerClass(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\context\support\WithSecurityContextTestExcecutionListenerTests.java)
Mock Object Variable Name: testContext
Suggested Diff
@@
Class testClass = OuterClass.InnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
- given(this.testContext.getTestClass()).willReturn(testClass);
- given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
- given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
+ this.testContext = createMockTestContext(testNoAnnotation);
+ given(this.testContext.getTestClass()).willReturn(testClass);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@@
Original Test Code (click to expand)
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodInnerClass() throws Exception {
Class testClass = OuterClass.InnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
Reusable Method for MCI (click to expand)
private static TestContext createMockTestContext(Method testMethod) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(testMethod);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
return testContext;
}
Test Case ID #spring-security_Test_9_4
Test Case Name: beforeTestMethodInnerInnerClass(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\context\support\WithSecurityContextTestExcecutionListenerTests.java)
Mock Object Variable Name: testContext
Suggested Diff
@@
Class testClass = OuterClass.InnerClass.InnerInnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
- given(this.testContext.getTestClass()).willReturn(testClass);
- given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
- given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
+ this.testContext = createMockTestContext(testNoAnnotation);
+ given(this.testContext.getTestClass()).willReturn(testClass);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@@
Original Test Code (click to expand)
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodInnerInnerClass() throws Exception {
Class testClass = OuterClass.InnerClass.InnerInnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
Reusable Method for MCI (click to expand)
private static TestContext createMockTestContext(Method testMethod) {
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(testMethod);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
return testContext;
}
Mock Clone Instance #spring-security_MCI_10
- Scope: class level
- Mocked Class:
org.springframework.web.client.RestClient
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockRestClient {
public static RestClient createMockRestClient(RestClient.RequestBodyUriSpec postReturn) {
RestClient mockRestClient = mock();
given(mockRestClient.post()).willReturn(postReturn);
return mockRestClient;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_10_1
Test Case Name: getTokenResponseWhenRestClientSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
- RestClient customClient = mock();
- given(customClient.post()).willReturn(RestClient.builder().build().post());
+ RestClient customClient = MockRestClient.createMockRestClient(RestClient.builder().build().post());
this.tokenResponseClient.setRestClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(customClient).post();
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenRestClientSetThenCalled() {
this.server.enqueue(MockResponses.json("access-token-response.json"));
RestClient customClient = mock();
given(customClient.post()).willReturn(RestClient.builder().build().post());
this.tokenResponseClient.setRestClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(customClient).post();
}
Reusable Method for MCI (click to expand)
public class MockRestClient {
public static RestClient createMockRestClient(RestClient.RequestBodyUriSpec postReturn) {
RestClient mockRestClient = mock();
given(mockRestClient.post()).willReturn(postReturn);
return mockRestClient;
}
}
Test Case ID #spring-security_Test_10_2
Test Case Name: getTokenResponseWhenRestClientSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
- RestClient customClient = mock();
- given(customClient.post()).willReturn(RestClient.builder().build().post());
+ RestClient customClient = MockRestClient.createMockRestClient(RestClient.builder().build().post());
this.tokenResponseClient.setRestClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(customClient).post();
}
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenRestClientSetThenCalled() {
this.server.enqueue(MockResponses.json("access-token-response.json"));
RestClient customClient = mock();
given(customClient.post()).willReturn(RestClient.builder().build().post());
this.tokenResponseClient.setRestClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(customClient).post();
}
Reusable Method for MCI (click to expand)
public class MockRestClient {
public static RestClient createMockRestClient(RestClient.RequestBodyUriSpec postReturn) {
RestClient mockRestClient = mock();
given(mockRestClient.post()).willReturn(postReturn);
return mockRestClient;
}
}
Mock Clone Instance #spring-security_MCI_11
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<JwtBearerGrantRequest, HttpHeaders> createMockHeadersConverter(JwtBearerGrantRequest request, HttpHeaders headers) {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_11_1
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, HttpHeaders> createMockHeadersConverter(JwtBearerGrantRequest request, HttpHeaders headers) {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_11_2
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, HttpHeaders> createMockHeadersConverter(JwtBearerGrantRequest request, HttpHeaders headers) {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_11_3
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
- given(headersConverter.convert(request)).willReturn(headers);
+ Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(request, headers);
this.client.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.client.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, HttpHeaders> createMockHeadersConverter(JwtBearerGrantRequest request, HttpHeaders headers) {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_11_4
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(addedHeadersConverter.convert(request)).willReturn(headers);
+ Converter<JwtBearerGrantRequest, HttpHeaders> addedHeadersConverter = MockConverter.createMockHeadersConverter(request, headers);
this.client.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.client.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, HttpHeaders> createMockHeadersConverter(JwtBearerGrantRequest request, HttpHeaders headers) {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Mock Clone Instance #spring-security_MCI_12
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static OpaqueTokenIntrospector createMockOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
return introspector;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_12_1
Test Case Name: authenticateWhenActiveTokenThenOk(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenAuthenticationProviderTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active((attributes) -> attributes.put("extension_field", "twenty-seven"));
- OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
- given(introspector.introspect(any())).willReturn(principal);
+ OpaqueTokenIntrospector introspector = createMockOpaqueTokenIntrospector(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
// @formatter:off
assertThat(attributes).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")).containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4").containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)).containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")).containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis").containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe").containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin");
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenActiveTokenThenOk() throws Exception {
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active((attributes) -> attributes.put("extension_field", "twenty-seven"));
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")).containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4").containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)).containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")).containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis").containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe").containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin");
}
Reusable Method for MCI (click to expand)
private static OpaqueTokenIntrospector createMockOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
return introspector;
}
Test Case ID #spring-security_Test_12_2
Test Case Name: authenticateWhenMissingScopeAttributeThenNoAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenAuthenticationProviderTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(Collections.singletonMap("claim", "value"), null);
- OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
- given(introspector.introspect(any())).willReturn(principal);
+ OpaqueTokenIntrospector introspector = createMockOpaqueTokenIntrospector(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2AuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
// @formatter:off
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
// @formatter:on
assertThat(result.getAuthorities()).isEmpty();
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenMissingScopeAttributeThenNoAuthorities() {
OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(Collections.singletonMap("claim", "value"), null);
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result.getPrincipal()).isInstanceOf(OAuth2AuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
assertThat(result.getAuthorities()).isEmpty();
}
Reusable Method for MCI (click to expand)
private static OpaqueTokenIntrospector createMockOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
return introspector;
}
Test Case ID #spring-security_Test_12_3
Test Case Name: authenticateWhenCustomAuthenticationConverterThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenAuthenticationProviderTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
public void authenticateWhenCustomAuthenticationConverterThenUses() {
- OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active();
- given(introspector.introspect(any())).willReturn(principal);
+ OpaqueTokenIntrospector introspector = createMockOpaqueTokenIntrospector(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
OpaqueTokenAuthenticationConverter authenticationConverter = mock(OpaqueTokenAuthenticationConverter.class);
given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))).willReturn(new TestingAuthenticationToken(principal, null, Collections.emptyList()));
provider.setAuthenticationConverter(authenticationConverter);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result).isNotNull();
verify(introspector).introspect("token");
verify(authenticationConverter).convert("token", principal);
verifyNoMoreInteractions(introspector, authenticationConverter);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenCustomAuthenticationConverterThenUses() {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active();
given(introspector.introspect(any())).willReturn(principal);
OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector);
OpaqueTokenAuthenticationConverter authenticationConverter = mock(OpaqueTokenAuthenticationConverter.class);
given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))).willReturn(new TestingAuthenticationToken(principal, null, Collections.emptyList()));
provider.setAuthenticationConverter(authenticationConverter);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token"));
assertThat(result).isNotNull();
verify(introspector).introspect("token");
verify(authenticationConverter).convert("token", principal);
verifyNoMoreInteractions(introspector, authenticationConverter);
}
Reusable Method for MCI (click to expand)
private static OpaqueTokenIntrospector createMockOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(principal);
return introspector;
}
Mock Clone Instance #spring-security_MCI_13
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.AuthorizationManager<org.aopalliance.intercept.MethodInvocation>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthorizationManager<MethodInvocation> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_13_1
Test Case Name: beforeWhenMockAuthorizationManagerThenCheck(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: mockAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
- AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
- given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<MethodInvocation> mockAuthorizationManager = createMockAuthorizationManager();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
advice.invoke(mockMethodInvocation);
verify(mockAuthorizationManager).check(any(Supplier.class), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void beforeWhenMockAuthorizationManagerThenCheck() throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
advice.invoke(mockMethodInvocation);
verify(mockAuthorizationManager).check(any(Supplier.class), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<MethodInvocation> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Test Case ID #spring-security_Test_13_2
Test Case Name: invokeWhenCustomAuthorizationDeniedExceptionThenThrows(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: manager
Suggested Diff
@@
@Test
public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() {
- AuthorizationManager<MethodInvocation> manager = mock(AuthorizationManager.class);
- given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
- given(manager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<MethodInvocation> manager = createMockAuthorizationManager();
+ given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(null));
}
@@
Original Test Code (click to expand)
@Test
public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() {
AuthorizationManager<MethodInvocation> manager = mock(AuthorizationManager.class);
given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
given(manager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> advice.invoke(null));
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<MethodInvocation> createMockAuthorizationManager() {
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_14
- Scope: method level
- Mocked Class:
org.springframework.security.acls.model.Acl
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Acl createMockAcl() {
Acl acl = mock(Acl.class);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
return acl;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_14_1
Test Case Name: hasPermissionReturnsTrueIfAclGrantsPermission(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: acl
Suggested Diff
@@
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
- Acl acl = mock(Acl.class);
+ Acl acl = createMockAcl();
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
- given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
Original Test Code (click to expand)
@Test
public void hasPermissionReturnsTrueIfAclGrantsPermission() {
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
Reusable Method for MCI (click to expand)
private static Acl createMockAcl() {
Acl acl = mock(Acl.class);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
return acl;
}
Test Case ID #spring-security_Test_14_2
Test Case Name: resolvePermissionNonEnglishLocale(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: acl
Suggested Diff
@@
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
- Acl acl = mock(Acl.class);
- given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
- given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
+ Acl acl = createMockAcl();
+ given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
@@
Original Test Code (click to expand)
@Test
public void resolvePermissionNonEnglishLocale() {
Locale systemLocale = Locale.getDefault();
Locale.setDefault(new Locale("tr"));
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
}
Reusable Method for MCI (click to expand)
private static Acl createMockAcl() {
Acl acl = mock(Acl.class);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
return acl;
}
Mock Clone Instance #spring-security_MCI_15
- Scope: method level
- Mocked Class:
org.springframework.security.acls.model.Acl
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Acl createMockAcl(boolean isGrantedReturn) {
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(isGrantedReturn);
return acl;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_15_1
Test Case Name: accessIsAllowedIfPermissionIsGranted(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationProviderTests.java)
Mock Object Variable Name: acl
Suggested Diff
@@
AclService service = mock(AclService.class);
- Acl acl = mock(Acl.class);
- given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true);
+ Acl acl = createMockAcl(true);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned));
@@
Original Test Code (click to expand)
@Test
public void accessIsAllowedIfPermissionIsGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
Reusable Method for MCI (click to expand)
private static Acl createMockAcl(boolean isGrantedReturn) {
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(isGrantedReturn);
return acl;
}
Test Case ID #spring-security_Test_15_2
Test Case Name: accessIsDeniedIfPermissionIsNotGranted(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationProviderTests.java)
Mock Object Variable Name: acl
Suggested Diff
@@
AclService service = mock(AclService.class);
- Acl acl = mock(Acl.class);
- given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false);
+ Acl acl = createMockAcl(false);
// Try a second time with no permissions found
given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException(""));
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
@@
Original Test Code (click to expand)
@Test
public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false);
given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException(""));
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setProcessConfigAttribute("MY_ATTRIBUTE");
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
}
Reusable Method for MCI (click to expand)
private static Acl createMockAcl(boolean isGrantedReturn) {
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(isGrantedReturn);
return acl;
}
Mock Clone Instance #spring-security_MCI_16
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.AuthenticationTrustResolver
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthenticationTrustResolver createMockAuthenticationTrustResolver(Authentication authentication, boolean isAuthenticatedReturn) {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
given(atr.isAuthenticated(authentication)).willReturn(isAuthenticatedReturn);
return atr;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_16_1
Test Case Name: isAuthenticatedWhenTrustResolverFalseThenFalse(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\expression\SecurityExpressionRootTests.java)
Mock Object Variable Name: atr
Suggested Diff
@@
void isAuthenticatedWhenTrustResolverFalseThenFalse() {
- AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
- given(atr.isAuthenticated(JOE)).willReturn(false);
+ AuthenticationTrustResolver atr = createMockAuthenticationTrustResolver(JOE, false);
this.root.setTrustResolver(atr);
assertThat(this.root.isAuthenticated()).isFalse();
}
Original Test Code (click to expand)
@Test
void isAuthenticatedWhenTrustResolverFalseThenFalse() {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
given(atr.isAuthenticated(JOE)).willReturn(false);
this.root.setTrustResolver(atr);
assertThat(this.root.isAuthenticated()).isFalse();
}
Reusable Method for MCI (click to expand)
private static AuthenticationTrustResolver createMockAuthenticationTrustResolver(Authentication authentication, boolean isAuthenticatedReturn) {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
given(atr.isAuthenticated(authentication)).willReturn(isAuthenticatedReturn);
return atr;
}
Test Case ID #spring-security_Test_16_2
Test Case Name: isAuthenticatedWhenTrustResolverTrueThenTrue(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\expression\SecurityExpressionRootTests.java)
Mock Object Variable Name: atr
Suggested Diff
@@
void isAuthenticatedWhenTrustResolverTrueThenTrue() {
- AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
- given(atr.isAuthenticated(JOE)).willReturn(true);
+ AuthenticationTrustResolver atr = createMockAuthenticationTrustResolver(JOE, true);
this.root.setTrustResolver(atr);
assertThat(this.root.isAuthenticated()).isTrue();
}
Original Test Code (click to expand)
@Test
void isAuthenticatedWhenTrustResolverTrueThenTrue() {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
given(atr.isAuthenticated(JOE)).willReturn(true);
this.root.setTrustResolver(atr);
assertThat(this.root.isAuthenticated()).isTrue();
}
Reusable Method for MCI (click to expand)
private static AuthenticationTrustResolver createMockAuthenticationTrustResolver(Authentication authentication, boolean isAuthenticatedReturn) {
AuthenticationTrustResolver atr = mock(AuthenticationTrustResolver.class);
given(atr.isAuthenticated(authentication)).willReturn(isAuthenticatedReturn);
return atr;
}
Mock Clone Instance #spring-security_MCI_17
- Scope: method level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2PasswordGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_17_1
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactivePasswordTokenResponseClientTests.java)
Mock Object Variable Name: addedParametersConverter
Suggested Diff
@@
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
- Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> addedParametersConverter = createMockParametersConverter(request, parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
String formParameters = actualRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, "password"), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
String formParameters = actualRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, "password"), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
private static Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2PasswordGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
Test Case ID #spring-security_Test_17_2
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactivePasswordTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
- Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(request)).willReturn(parameters);
+ Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = createMockParametersConverter(request, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
private static Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2PasswordGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2PasswordGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
Mock Clone Instance #spring-security_MCI_18
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.core.user.OAuth2User
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static OAuth2User createMockOAuth2User(List<GrantedAuthority> authorities) {
OAuth2User principal = mock(OAuth2User.class);
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
return principal;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_18_1
Test Case Name: authenticateWhenLoginSuccessThenReturnAuthentication(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
- OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OAuth2User principal = createMockOAuth2User(authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getPrincipal()).isEqualTo(principal);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getPrincipal()).isEqualTo(principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(authorities);
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authentication.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
Reusable Method for MCI (click to expand)
private static OAuth2User createMockOAuth2User(List<GrantedAuthority> authorities) {
OAuth2User principal = mock(OAuth2User.class);
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
return principal;
}
Test Case ID #spring-security_Test_18_2
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
- OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OAuth2User principal = createMockOAuth2User(authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
private static OAuth2User createMockOAuth2User(List<GrantedAuthority> authorities) {
OAuth2User principal = mock(OAuth2User.class);
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
return principal;
}
Test Case ID #spring-security_Test_18_3
Test Case Name: authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
- OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OAuth2User principal = createMockOAuth2User(authorities);
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
Reusable Method for MCI (click to expand)
private static OAuth2User createMockOAuth2User(List<GrantedAuthority> authorities) {
OAuth2User principal = mock(OAuth2User.class);
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
return principal;
}
Mock Clone Instance #spring-security_MCI_19
- Scope: method level
- Mocked Class:
org.springframework.security.config.ObjectPostProcessor<java.lang.Object>
- Test Case Count: 4
- MO Count: 4
Reusable Method
private ObjectPostProcessor<Object> opp;
@BeforeEach
public void setUp() {
opp = mock(ObjectPostProcessor.class);
}
opp
The refactoring details in each test cases
Test Case ID #spring-security_Test_19_1
Mock Object Variable Name: opp
Suggested Diff
@@
@Test
public void buildWhenAddAuthenticationProviderThenDoesNotPerformRegistration() throws Exception {
- ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
+ // removed local mock; replaced with global field `opp`
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
verify(opp, never()).postProcess(provider);
}
Original Test Code (click to expand)
@Test
public void buildWhenAddAuthenticationProviderThenDoesNotPerformRegistration() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
verify(opp, never()).postProcess(provider);
}
Reusable Method for MCI (click to expand)
private ObjectPostProcessor<Object> opp;
@BeforeEach
public void setUp() {
opp = mock(ObjectPostProcessor.class);
}
opp
Test Case ID #spring-security_Test_19_2
Mock Object Variable Name: opp
Suggested Diff
@@
@Test
public void buildWhenAuthenticationProviderThenIsConfigured() throws Exception {
- ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
+ // removed local mock; replaced with global field `opp`
AuthenticationProvider provider = mock(AuthenticationProvider.class);
- AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
+ AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
Original Test Code (click to expand)
@Test
public void buildWhenAuthenticationProviderThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
Reusable Method for MCI (click to expand)
private ObjectPostProcessor<Object> opp;
@BeforeEach
public void setUp() {
opp = mock(ObjectPostProcessor.class);
}
opp
Test Case ID #spring-security_Test_19_3
Mock Object Variable Name: opp
Suggested Diff
@@
@Test
public void buildWhenParentThenIsConfigured() throws Exception {
- ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
+ // removed local mock; replaced with global field `opp`
AuthenticationManager parent = mock(AuthenticationManager.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.parentAuthenticationManager(parent);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
Original Test Code (click to expand)
@Test
public void buildWhenParentThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.parentAuthenticationManager(parent);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
Reusable Method for MCI (click to expand)
private ObjectPostProcessor<Object> opp;
@BeforeEach
public void setUp() {
opp = mock(ObjectPostProcessor.class);
}
opp
Test Case ID #spring-security_Test_19_4
Mock Object Variable Name: opp
Suggested Diff
@@
@Test
public void buildWhenNotConfiguredThenIsConfiguredFalse() throws Exception {
- ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
+ // removed local mock; replaced with global field `opp`
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.build();
assertThat(builder.isConfigured()).isFalse();
}
Original Test Code (click to expand)
@Test
public void buildWhenNotConfiguredThenIsConfiguredFalse() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.build();
assertThat(builder.isConfigured()).isFalse();
}
Reusable Method for MCI (click to expand)
private ObjectPostProcessor<Object> opp;
@BeforeEach
public void setUp() {
opp = mock(ObjectPostProcessor.class);
}
opp
Mock Clone Instance #spring-security_MCI_20
- Scope: method level
- Mocked Class:
com.nimbusds.jose.jwk.source.JWKSource<com.nimbusds.jose.proc.SecurityContext>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static JWKSource<SecurityContext> createMockJwkSource(List<RSAKey> keysToReturn) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(keysToReturn);
return jwkSource;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_20_1
Test Case Name: getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\JwtDecoderProviderConfigurationUtilsTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses() throws Exception {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(JWSAlgorithm.RS384).build();
- given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
+ JWKSource<SecurityContext> jwkSource = createMockJwkSource(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS384);
}
@@
Original Test Code (click to expand)
@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(JWSAlgorithm.RS384).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS384);
}
Reusable Method for MCI (click to expand)
private static JWKSource<SecurityContext> createMockJwkSource(List<RSAKey> keysToReturn) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(keysToReturn);
return jwkSource;
}
Test Case ID #spring-security_Test_20_2
Test Case Name: getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\JwtDecoderProviderConfigurationUtilsTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
public void getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses() throws Exception {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
// Test parameters are from Anders Rundgren, public only
ECKey ecKey = new ECKey.Builder(Curve.P_256, new Base64URL("3l2Da_flYc-AuUTm2QzxgyvJxYM_2TeB9DMlwz7j1PE"), new Base64URL("-kjT7Wrfhwsi9SG6H4UXiyUiVE9GHCLauslksZ3-_t0")).keyUse(KeyUse.SIGNATURE).build();
RSAKey rsaKey = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.ENCRYPTION).build();
- given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Arrays.asList(ecKey, rsaKey));
+ JWKSource<SecurityContext> jwkSource = createMockJwkSource(Arrays.asList(ecKey, rsaKey));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).contains(SignatureAlgorithm.ES256, SignatureAlgorithm.ES384, SignatureAlgorithm.ES512);
}
Original Test Code (click to expand)
@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
ECKey ecKey = new ECKey.Builder(Curve.P_256, new Base64URL("3l2Da_flYc-AuUTm2QzxgyvJxYM_2TeB9DMlwz7j1PE"), new Base64URL("-kjT7Wrfhwsi9SG6H4UXiyUiVE9GHCLauslksZ3-_t0")).keyUse(KeyUse.SIGNATURE).build();
RSAKey rsaKey = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.ENCRYPTION).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Arrays.asList(ecKey, rsaKey));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).contains(SignatureAlgorithm.ES256, SignatureAlgorithm.ES384, SignatureAlgorithm.ES512);
}
Reusable Method for MCI (click to expand)
private static JWKSource<SecurityContext> createMockJwkSource(List<RSAKey> keysToReturn) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(keysToReturn);
return jwkSource;
}
Test Case ID #spring-security_Test_20_3
Test Case Name: getSignatureAlgorithmsWhenAlgorithmThenParses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\JwtDecoderProviderConfigurationUtilsTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
// gh-9651
@Test
public void getSignatureAlgorithmsWhenAlgorithmThenParses() throws Exception {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(new Algorithm(JwsAlgorithms.RS256)).build();
- given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
+ JWKSource<SecurityContext> jwkSource = createMockJwkSource(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS256);
}
@@
Original Test Code (click to expand)
@Test
public void getSignatureAlgorithmsWhenAlgorithmThenParses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE).algorithm(new Algorithm(JwsAlgorithms.RS256)).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS256);
}
Reusable Method for MCI (click to expand)
private static JWKSource<SecurityContext> createMockJwkSource(List<RSAKey> keysToReturn) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(keysToReturn);
return jwkSource;
}
Mock Clone Instance #spring-security_MCI_21
- Scope: class level
- Mocked Class:
com.nimbusds.jose.jwk.source.JWKSource<com.nimbusds.jose.proc.SecurityContext>
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockJWKSource {
public static JWKSource<SecurityContext> createMockJwkSource(List<JWK> jwkList) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(jwkList);
return jwkSource;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_21_1
Test Case Name: withJwkSourceWhenDefaultsThenUsesProvidedJwkSource(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: source
Suggested Diff
@@
public void withJwkSourceWhenDefaultsThenUsesProvidedJwkSource() throws Exception {
- JWKSource<SecurityContext> source = mock(JWKSource.class);
- given(source.get(any(), any())).willReturn(JWKSet.parse(JWK_SET).getKeys());
+ JWKSource<SecurityContext> source = MockJWKSource.createMockJwkSource(JWKSet.parse(JWK_SET).getKeys());
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSource(source).build();
Jwt jwt = decoder.decode(SIGNED_JWT);
assertThat(jwt.getClaimAsString("sub")).isEqualTo("test-subject");
}
Original Test Code (click to expand)
@Test
public void withJwkSourceWhenDefaultsThenUsesProvidedJwkSource() throws Exception {
JWKSource<SecurityContext> source = mock(JWKSource.class);
given(source.get(any(), any())).willReturn(JWKSet.parse(JWK_SET).getKeys());
NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSource(source).build();
Jwt jwt = decoder.decode(SIGNED_JWT);
assertThat(jwt.getClaimAsString("sub")).isEqualTo("test-subject");
}
Reusable Method for MCI (click to expand)
public class MockJWKSource {
public static JWKSource<SecurityContext> createMockJwkSource(List<JWK> jwkList) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(jwkList);
return jwkSource;
}
}
Test Case ID #spring-security_Test_21_2
Test Case Name: encodeWhenMultipleKeysThenJwkSelectorUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtEncoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
JWK jwk = TestJwks.rsa().algorithm(JWSAlgorithm.RS256).build();
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
- given(jwkSource.get(any(), any())).willReturn(List.of(jwk, jwk));
+ JWKSource<SecurityContext> jwkSource = MockJWKSource.createMockJwkSource(List.of(jwk, jwk));
Converter<List<JWK>, JWK> selector = mock(Converter.class);
Original Test Code (click to expand)
@Test
public void encodeWhenMultipleKeysThenJwkSelectorUsed() throws Exception {
JWK jwk = TestJwks.rsa().algorithm(JWSAlgorithm.RS256).build();
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(List.of(jwk, jwk));
Converter<List<JWK>, JWK> selector = mock(Converter.class);
given(selector.convert(any())).willReturn(TestJwks.DEFAULT_RSA_JWK);
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);
jwtEncoder.setJwkSelector(selector);
JwtClaimsSet claims = JwtClaimsSet.builder().subject("sub").build();
jwtEncoder.encode(JwtEncoderParameters.from(claims));
verify(selector).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockJWKSource {
public static JWKSource<SecurityContext> createMockJwkSource(List<JWK> jwkList) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(jwkList);
return jwkSource;
}
}
Test Case ID #spring-security_Test_21_3
Test Case Name: encodeWhenSingleKeyThenJwkSelectorIsNotUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtEncoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
JWK jwk = TestJwks.rsa().algorithm(JWSAlgorithm.RS256).build();
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
- given(jwkSource.get(any(), any())).willReturn(List.of(jwk));
+ JWKSource<SecurityContext> jwkSource = MockJWKSource.createMockJwkSource(List.of(jwk));
Converter<List<JWK>, JWK> selector = mock(Converter.class);
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);
jwtEncoder.setJwkSelector(selector);
JwtClaimsSet claims = JwtClaimsSet.builder().subject("sub").build();
jwtEncoder.encode(JwtEncoderParameters.from(claims));
verifyNoInteractions(selector);
}
Original Test Code (click to expand)
@Test
public void encodeWhenSingleKeyThenJwkSelectorIsNotUsed() throws Exception {
JWK jwk = TestJwks.rsa().algorithm(JWSAlgorithm.RS256).build();
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(List.of(jwk));
Converter<List<JWK>, JWK> selector = mock(Converter.class);
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSource);
jwtEncoder.setJwkSelector(selector);
JwtClaimsSet claims = JwtClaimsSet.builder().subject("sub").build();
jwtEncoder.encode(JwtEncoderParameters.from(claims));
verifyNoInteractions(selector);
}
Reusable Method for MCI (click to expand)
public class MockJWKSource {
public static JWKSource<SecurityContext> createMockJwkSource(List<JWK> jwkList) {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(), any())).willReturn(jwkList);
return jwkSource;
}
}
Mock Clone Instance #spring-security_MCI_22
- Scope: method level
- Mocked Class:
com.nimbusds.jose.jwk.source.JWKSource<com.nimbusds.jose.proc.SecurityContext>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private JWKSource<SecurityContext> jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(JWKSource.class);
}
jwkSource;
The refactoring details in each test cases
Test Case ID #spring-security_Test_22_1
Test Case Name: jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsKeySelector(jwkSource);
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsKeySelector(jwkSource);
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
Reusable Method for MCI (click to expand)
private JWKSource<SecurityContext> jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(JWKSource.class);
}
jwkSource;
Test Case ID #spring-security_Test_22_2
Test Case Name: jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
// @formatter:off
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource);
// @formatter:on
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource);
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Reusable Method for MCI (click to expand)
private JWKSource<SecurityContext> jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(JWKSource.class);
}
jwkSource;
Test Case ID #spring-security_Test_22_3
Test Case Name: jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
- JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
// @formatter:off
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource);
// @formatter:on
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource);
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Reusable Method for MCI (click to expand)
private JWKSource<SecurityContext> jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(JWKSource.class);
}
jwkSource;
Mock Clone Instance #spring-security_MCI_23
- Scope: class level
- Mocked Class:
org.springframework.security.web.csrf.CsrfTokenRepository
- Test Case Count: 2
- MO Count: 2
Reusable Method
public class MockCsrfTokenRepository {
public static CsrfTokenRepository createMockCsrfTokenRepository(MockHttpServletRequest request, CsrfToken token) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
when(csrfTokenRepository.generateToken(request)).thenReturn(token);
return csrfTokenRepository;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_23_1
Test Case Name: delaySavingCsrf(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\csrf\CsrfAuthenticationStrategyTests.java)
Mock Object Variable Name: csrfTokenRepository
Suggested Diff
@@
public void delaySavingCsrf() {
this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository));
- given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken, (CsrfToken) null);
- given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
+ this.csrfTokenRepository = MockCsrfTokenRepository.createMockCsrfTokenRepository(this.request, this.generatedToken);
+ given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken, (CsrfToken) null);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName());
tokenInRequest.getToken();
verify(this.csrfTokenRepository, times(2)).loadToken(this.request);
verify(this.csrfTokenRepository).generateToken(this.request);
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Original Test Code (click to expand)
@Test
public void delaySavingCsrf() {
this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository));
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken, (CsrfToken) null);
given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request, this.response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName());
tokenInRequest.getToken();
verify(this.csrfTokenRepository, times(2)).loadToken(this.request);
verify(this.csrfTokenRepository).generateToken(this.request);
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
public class MockCsrfTokenRepository {
public static CsrfTokenRepository createMockCsrfTokenRepository(MockHttpServletRequest request, CsrfToken token) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
when(csrfTokenRepository.generateToken(request)).thenReturn(token);
return csrfTokenRepository;
}
}
Test Case ID #spring-security_Test_23_2
Test Case Name: doFilterDoesNotSaveCsrfTokenUntilAccessed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\csrf\CsrfFilterTests.java)
Mock Object Variable Name: tokenRepository
Suggested Diff
@@
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException {
- this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
+ this.tokenRepository = MockCsrfTokenRepository.createMockCsrfTokenRepository(this.request, this.token);
+ this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
given(this.requestMatcher.matches(this.request)).willReturn(false);
- given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.csrfAttrName);
// no CsrfToken should have been saved yet
verify(this.tokenRepository, times(0)).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filterChain).doFilter(this.request, this.response);
// access the token
attrToken.getToken();
// now the CsrfToken should have been saved
verify(this.tokenRepository).saveToken(eq(this.token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@
Original Test Code (click to expand)
@Test
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException {
this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.csrfAttrName);
verify(this.tokenRepository, times(0)).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filterChain).doFilter(this.request, this.response);
attrToken.getToken();
verify(this.tokenRepository).saveToken(eq(this.token), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
public class MockCsrfTokenRepository {
public static CsrfTokenRepository createMockCsrfTokenRepository(MockHttpServletRequest request, CsrfToken token) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
when(csrfTokenRepository.generateToken(request)).thenReturn(token);
return csrfTokenRepository;
}
}
Mock Clone Instance #spring-security_MCI_24
- Scope: method level
- Mocked Class:
org.springframework.security.web.csrf.CsrfTokenRepository
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static CsrfTokenRepository createMockCsrfTokenRepository(DeferredCsrfToken deferredCsrfToken) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(deferredCsrfToken);
return csrfTokenRepository;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_24_1
Mock Object Variable Name: csrfTokenRepository
Suggested Diff
@@
@Test
public void getLoginWhenCsrfTokenRequestAttributeHandlerSetThenRespondsWithNormalCsrfToken() throws Exception {
- CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
- given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
+ CsrfTokenRepository csrfTokenRepository = createMockCsrfTokenRepository(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()).andExpect(content().string(containsString(csrfToken.getToken())));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
}
@@
Original Test Code (click to expand)
@Test
public void getLoginWhenCsrfTokenRequestAttributeHandlerSetThenRespondsWithNormalCsrfToken() throws Exception {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()).andExpect(content().string(containsString(csrfToken.getToken())));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
}
Reusable Method for MCI (click to expand)
private static CsrfTokenRepository createMockCsrfTokenRepository(DeferredCsrfToken deferredCsrfToken) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(deferredCsrfToken);
return csrfTokenRepository;
}
Test Case ID #spring-security_Test_24_2
Mock Object Variable Name: csrfTokenRepository
Suggested Diff
@@
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
- CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
- given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
- given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
+ CsrfTokenRepository csrfTokenRepository = createMockCsrfTokenRepository(new TestDeferredCsrfToken(csrfToken));
+ given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
// @formatter:off
MockHttpServletRequestBuilder loginRequest = post("/login").header(csrfToken.getHeaderName(), csrfToken.getToken()).param("username", "user").param("password", "password");
// @formatter:on
this.mvc.perform(loginRequest).andExpect(redirectedUrl("/"));
verify(csrfTokenRepository).loadToken(any(HttpServletRequest.class));
verify(csrfTokenRepository).saveToken(isNull(), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(csrfTokenRepository, times(2)).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
@@
Original Test Code (click to expand)
@Test
public void loginWhenCsrfTokenRequestAttributeHandlerSetAndNormalCsrfTokenThenSuccess() throws Exception {
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
MockHttpServletRequestBuilder loginRequest = post("/login").header(csrfToken.getHeaderName(), csrfToken.getToken()).param("username", "user").param("password", "password");
this.mvc.perform(loginRequest).andExpect(redirectedUrl("/"));
verify(csrfTokenRepository).loadToken(any(HttpServletRequest.class));
verify(csrfTokenRepository).saveToken(isNull(), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(csrfTokenRepository, times(2)).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
}
Reusable Method for MCI (click to expand)
private static CsrfTokenRepository createMockCsrfTokenRepository(DeferredCsrfToken deferredCsrfToken) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(deferredCsrfToken);
return csrfTokenRepository;
}
Test Case ID #spring-security_Test_24_3
Mock Object Variable Name: csrfTokenRepository
Suggested Diff
@@
public void getLoginWhenXorCsrfTokenRequestAttributeHandlerSetThenRespondsWithMaskedCsrfToken() throws Exception {
- CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
- given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
+ CsrfTokenRepository csrfTokenRepository = createMockCsrfTokenRepository(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()).andExpect(content().string(not(containsString(csrfToken.getToken()))));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
@@
Original Test Code (click to expand)
@Test
public void getLoginWhenXorCsrfTokenRequestAttributeHandlerSetThenRespondsWithMaskedCsrfToken() throws Exception {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/login")).andExpect(status().isOk()).andExpect(content().string(not(containsString(csrfToken.getToken()))));
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
}
Reusable Method for MCI (click to expand)
private static CsrfTokenRepository createMockCsrfTokenRepository(DeferredCsrfToken deferredCsrfToken) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(deferredCsrfToken);
return csrfTokenRepository;
}
Test Case ID #spring-security_Test_24_4
Mock Object Variable Name: csrfTokenRepository
Suggested Diff
@@
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
- CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
- given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
- given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
+ CsrfTokenRepository csrfTokenRepository = createMockCsrfTokenRepository(new TestDeferredCsrfToken(csrfToken));
+ given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/login")).andReturn();
CsrfToken csrfTokenAttribute = (CsrfToken) mvcResult.getRequest().getAttribute(CsrfToken.class.getName());
// @formatter:off
MockHttpServletRequestBuilder loginRequest = post("/login").header(csrfToken.getHeaderName(), csrfTokenAttribute.getToken()).param("username", "user").param("password", "password");
// @formatter:on
this.mvc.perform(loginRequest).andExpect(redirectedUrl("/"));
verify(csrfTokenRepository).loadToken(any(HttpServletRequest.class));
verify(csrfTokenRepository).saveToken(isNull(), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(csrfTokenRepository, times(3)).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
@@
Original Test Code (click to expand)
@Test
public void loginWhenXorCsrfTokenRequestAttributeHandlerSetAndMaskedCsrfTokenThenSuccess() throws Exception {
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/login")).andReturn();
CsrfToken csrfTokenAttribute = (CsrfToken) mvcResult.getRequest().getAttribute(CsrfToken.class.getName());
MockHttpServletRequestBuilder loginRequest = post("/login").header(csrfToken.getHeaderName(), csrfTokenAttribute.getToken()).param("username", "user").param("password", "password");
this.mvc.perform(loginRequest).andExpect(redirectedUrl("/"));
verify(csrfTokenRepository).loadToken(any(HttpServletRequest.class));
verify(csrfTokenRepository).saveToken(isNull(), any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(csrfTokenRepository, times(3)).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(csrfTokenRepository);
}
Reusable Method for MCI (click to expand)
private static CsrfTokenRepository createMockCsrfTokenRepository(DeferredCsrfToken deferredCsrfToken) {
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class))).willReturn(deferredCsrfToken);
return csrfTokenRepository;
}
Mock Clone Instance #spring-security_MCI_25
- Scope: method level
- Mocked Class:
jakarta.servlet.http.HttpServletRequest
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static HttpServletRequest createMockHttpServletRequest(String forwardPath, RequestDispatcher dispatcher) {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getRequestDispatcher(forwardPath)).willReturn(dispatcher);
return request;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_25_1
Test Case Name: resetWhenForward(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\firewall\RequestWrapperTests.java)
Mock Object Variable Name: mockRequest
Suggested Diff
@@
String denormalizedPath = testPaths.keySet().iterator().next();
String forwardPath = "/forward/path";
- HttpServletRequest mockRequest = mock(HttpServletRequest.class);
+ HttpServletRequest mockRequest = createMockHttpServletRequest(forwardPath, mockDispatcher);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
RequestDispatcher mockDispatcher = mock(RequestDispatcher.class);
- given(mockRequest.getServletPath()).willReturn("");
- given(mockRequest.getPathInfo()).willReturn(denormalizedPath);
- given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher);
+ given(mockRequest.getServletPath()).willReturn("");
+ given(mockRequest.getPathInfo()).willReturn(denormalizedPath);
RequestWrapper wrapper = new RequestWrapper(mockRequest);
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
dispatcher.forward(mockRequest, mockResponse);
verify(mockRequest).getRequestDispatcher(forwardPath);
verify(mockDispatcher).forward(mockRequest, mockResponse);
assertThat(wrapper.getPathInfo()).isEqualTo(denormalizedPath);
verify(mockRequest, times(2)).getPathInfo();
// validate wrapper.getServletPath() delegates to the mock
wrapper.getServletPath();
verify(mockRequest, times(2)).getServletPath();
verifyNoMoreInteractions(mockRequest, mockResponse, mockDispatcher);
@@
Original Test Code (click to expand)
@Test
public void resetWhenForward() throws Exception {
String denormalizedPath = testPaths.keySet().iterator().next();
String forwardPath = "/forward/path";
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
RequestDispatcher mockDispatcher = mock(RequestDispatcher.class);
given(mockRequest.getServletPath()).willReturn("");
given(mockRequest.getPathInfo()).willReturn(denormalizedPath);
given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher);
RequestWrapper wrapper = new RequestWrapper(mockRequest);
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
dispatcher.forward(mockRequest, mockResponse);
verify(mockRequest).getRequestDispatcher(forwardPath);
verify(mockDispatcher).forward(mockRequest, mockResponse);
assertThat(wrapper.getPathInfo()).isEqualTo(denormalizedPath);
verify(mockRequest, times(2)).getPathInfo();
wrapper.getServletPath();
verify(mockRequest, times(2)).getServletPath();
verifyNoMoreInteractions(mockRequest, mockResponse, mockDispatcher);
}
Reusable Method for MCI (click to expand)
private static HttpServletRequest createMockHttpServletRequest(String forwardPath, RequestDispatcher dispatcher) {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getRequestDispatcher(forwardPath)).willReturn(dispatcher);
return request;
}
Test Case ID #spring-security_Test_25_2
Test Case Name: requestDispatcherNotWrappedAfterReset(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\firewall\RequestWrapperTests.java)
Mock Object Variable Name: request
Suggested Diff
@@
String path = "/forward/path";
- HttpServletRequest request = mock(HttpServletRequest.class);
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
- given(request.getRequestDispatcher(path)).willReturn(dispatcher);
+ HttpServletRequest request = createMockHttpServletRequest(path, dispatcher);
RequestWrapper wrapper = new RequestWrapper(request);
wrapper.reset();
assertThat(wrapper.getRequestDispatcher(path)).isSameAs(dispatcher);
@@
Original Test Code (click to expand)
@Test
public void requestDispatcherNotWrappedAfterReset() {
String path = "/forward/path";
HttpServletRequest request = mock(HttpServletRequest.class);
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
given(request.getRequestDispatcher(path)).willReturn(dispatcher);
RequestWrapper wrapper = new RequestWrapper(request);
wrapper.reset();
assertThat(wrapper.getRequestDispatcher(path)).isSameAs(dispatcher);
}
Reusable Method for MCI (click to expand)
private static HttpServletRequest createMockHttpServletRequest(String forwardPath, RequestDispatcher dispatcher) {
HttpServletRequest request = mock(HttpServletRequest.class);
given(request.getRequestDispatcher(forwardPath)).willReturn(dispatcher);
return request;
}
Mock Clone Instance #spring-security_MCI_26
- Scope: method level
- Mocked Class:
jakarta.servlet.http.HttpServletRequest
- Test Case Count: 7
- MO Count: 7
Reusable Method
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
The refactoring details in each test cases
Test Case ID #spring-security_Test_26_1
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenResultDoesNotDelegateToSetAttribute() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
verifyNoInteractions(request);
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
}
Original Test Code (click to expand)
@Test
void transformThenResultDoesNotDelegateToSetAttribute() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
verifyNoInteractions(request);
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_2
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenSetAttributeWorks() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
}
Original Test Code (click to expand)
@Test
void transformThenSetAttributeWorks() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
assertThat(transformedRequest.getAttribute(attrName)).isEqualTo(attrValue);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_3
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenResultDoesNotDelegateToGetAttribute() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.getAttribute("any");
verifyNoInteractions(request);
Original Test Code (click to expand)
@Test
void transformThenResultDoesNotDelegateToGetAttribute() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.getAttribute("any");
verifyNoInteractions(request);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_4
Mock Object Variable Name: request
Suggested Diff
@@
*/
@Test
void transformThenResultDoesNotDelegateToGetAttributeNames() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.getAttributeNames();
verifyNoInteractions(request);
}
Original Test Code (click to expand)
@Test
void transformThenResultDoesNotDelegateToGetAttributeNames() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.getAttributeNames();
verifyNoInteractions(request);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_5
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenGetAttributeNamesWorks() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
assertThat(Collections.list(transformedRequest.getAttributeNames())).containsExactly(attrName);
}
Original Test Code (click to expand)
@Test
void transformThenGetAttributeNamesWorks() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
String attrName = "any";
String attrValue = "value";
transformedRequest.setAttribute(attrName, attrValue);
assertThat(Collections.list(transformedRequest.getAttributeNames())).containsExactly(attrName);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_6
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenResultDoesNotDelegateToRemoveAttribute() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.removeAttribute("any");
verifyNoInteractions(request);
Original Test Code (click to expand)
@Test
void transformThenResultDoesNotDelegateToRemoveAttribute() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
transformedRequest.removeAttribute("any");
verifyNoInteractions(request);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Test Case ID #spring-security_Test_26_7
Mock Object Variable Name: request
Suggested Diff
@@
@Test
void transformThenResultDoesNotDelegateToGetDispatcherType() {
- HttpServletRequest request = mock(HttpServletRequest.class);
+ // removed local mock; replaced with global field `request`
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
assertThat(transformedRequest.getDispatcherType()).isEqualTo(DispatcherType.REQUEST);
verifyNoInteractions(request);
}
Original Test Code (click to expand)
@Test
void transformThenResultDoesNotDelegateToGetDispatcherType() {
HttpServletRequest request = mock(HttpServletRequest.class);
this.transformer.transform(request);
ArgumentCaptor<HttpServletRequest> requestArg = ArgumentCaptor.forClass(HttpServletRequest.class);
verify(this.hmi).setCache(requestArg.capture());
HttpServletRequest transformedRequest = requestArg.getValue();
assertThat(transformedRequest.getDispatcherType()).isEqualTo(DispatcherType.REQUEST);
verifyNoInteractions(request);
}
Reusable Method for MCI (click to expand)
private HttpServletRequest request;
@BeforeEach
public void setUp() {
request = mock(HttpServletRequest.class);
}
request
Mock Clone Instance #spring-security_MCI_27
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.method.AuthorizationManagerBeforeReactiveMethodInterceptorTests.HandlingReactiveAuthorizationManager
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(MethodInvocation mockMethodInvocation, Mono<?> checkReturnMono) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(checkReturnMono);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_27_1
Test Case Name: invokeMonoWhenDeniedAndPostProcessorThenInvokePostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
- given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn("***");
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(mockMethodInvocation, Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn("***");
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenDeniedAndPostProcessorThenInvokePostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn("***");
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(MethodInvocation mockMethodInvocation, Mono<?> checkReturnMono) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(checkReturnMono);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_27_2
Test Case Name: invokeMonoWhenDeniedAndMonoPostProcessorThenInvokePostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
- given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(mockMethodInvocation, Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenDeniedAndMonoPostProcessorThenInvokePostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(MethodInvocation mockMethodInvocation, Mono<?> checkReturnMono) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(checkReturnMono);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_27_3
Test Case Name: invokeFluxWhenDeniedAndPostProcessorThenInvokePostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
- given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(mockMethodInvocation, Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenDeniedAndPostProcessorThenInvokePostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
given(mockReactiveAuthorizationManager.handleDeniedInvocation(any(), any(AuthorizationResult.class))).willReturn(Mono.just("***"));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("***");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(MethodInvocation mockMethodInvocation, Mono<?> checkReturnMono) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(checkReturnMono);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_28
- Scope: method level
- Mocked Class:
org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
- Test Case Count: 3
- MO Count: 3
Reusable Method
private RelyingPartyRegistrationRepository registrations;
@BeforeEach
public void setUp() {
registrations = mock(RelyingPartyRegistrationRepository.class);
}
registrations
The refactoring details in each test cases
Test Case ID #spring-security_Test_28_1
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
void saml2MetadataResolveWhenNoMatchingRegistrationThenNull() {
- RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
+ // removed local mock; replaced with global field `registrations`
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
MockHttpServletRequest request = get("/saml2/metadata");
Saml2MetadataResponse response = resolver.resolve(request);
assertThat(response).isNull();
}
Original Test Code (click to expand)
@Test
void saml2MetadataResolveWhenNoMatchingRegistrationThenNull() {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
MockHttpServletRequest request = get("/saml2/metadata");
Saml2MetadataResponse response = resolver.resolve(request);
assertThat(response).isNull();
}
Reusable Method for MCI (click to expand)
private RelyingPartyRegistrationRepository registrations;
@BeforeEach
public void setUp() {
registrations = mock(RelyingPartyRegistrationRepository.class);
}
registrations
Test Case ID #spring-security_Test_28_2
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
void saml2MetadataRegistrationIdResolveWhenNoMatchingRegistrationThenException() {
- RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
+ // removed local mock; replaced with global field `registrations`
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
MockHttpServletRequest request = get("/saml2/metadata/id");
assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> resolver.resolve(request));
}
Original Test Code (click to expand)
@Test
void saml2MetadataRegistrationIdResolveWhenNoMatchingRegistrationThenException() {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
MockHttpServletRequest request = get("/saml2/metadata/id");
assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> resolver.resolve(request));
}
Reusable Method for MCI (click to expand)
private RelyingPartyRegistrationRepository registrations;
@BeforeEach
public void setUp() {
registrations = mock(RelyingPartyRegistrationRepository.class);
}
registrations
Test Case ID #spring-security_Test_28_3
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
void resolveWhenRequestDoesNotMatchThenNull() {
- RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
+ // removed local mock; replaced with global field `registrations`
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
assertThat(resolver.resolve(new MockHttpServletRequest())).isNull();
}
Original Test Code (click to expand)
@Test
void resolveWhenRequestDoesNotMatchThenNull() {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory);
assertThat(resolver.resolve(new MockHttpServletRequest())).isNull();
}
Reusable Method for MCI (click to expand)
private RelyingPartyRegistrationRepository registrations;
@BeforeEach
public void setUp() {
registrations = mock(RelyingPartyRegistrationRepository.class);
}
registrations
Mock Clone Instance #spring-security_MCI_29
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
- Test Case Count: 9
- MO Count: 9
Reusable Method
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_29_1
Test Case Name: saml2LogoutRegistrationIdResolveWhenMatchesThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdResolveWhenMatchesThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_2
Test Case Name: saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_3
Test Case Name: saml2LogoutResolveWhenAuthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenAuthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_4
Test Case Name: saml2LogoutRegistrationIdResolveWhenMatchesThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSamlLogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdResolveWhenMatchesThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_5
Test Case Name: saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSamlLogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
@@
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_6
Test Case Name: saml2LogoutResolveWhenAuthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSamlLogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenAuthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_7
Test Case Name: saml2LogoutRegistrationIdResolveWhenMatchesThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
@@
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdResolveWhenMatchesThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_8
Test Case Name: saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Original Test Code (click to expand)
@Test
void saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_29_9
Test Case Name: saml2LogoutResolveWhenAuthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
- given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(registrationId, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenAuthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
Authentication authentication = TestSaml2Authentications.authentication();
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication);
assertThat(parameters.getAuthentication()).isEqualTo(authentication);
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request");
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String registrationId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = Mockito.mock(RelyingPartyRegistrationRepository.class);
BDDMockito.given(registrations.findByRegistrationId(registrationId)).willReturn(registration);
return registrations;
}
}
Mock Clone Instance #spring-security_MCI_30
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
- Test Case Count: 6
- MO Count: 6
Reusable Method
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_30_1
Test Case Name: saml2LogoutResolveWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_30_2
Test Case Name: saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(
+ TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = get("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_30_3
Test Case Name: saml2LogoutResolveWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSamlLogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_30_4
Test Case Name: saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSamlLogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = get("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(
+ TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = get("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_30_5
Test Case Name: saml2LogoutResolveWhenUnauthenticatedThenParameters(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedThenParameters() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = post("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_30_6
Test Case Name: saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestValidatorParametersResolverTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = get("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(
+ TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
Original Test Code (click to expand)
@Test
void saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates() {
String registrationId = this.registration.getRegistrationId();
MockHttpServletRequest request = get("/logout/saml2/slo");
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest());
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest));
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded);
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null);
assertThat(parameters.getAuthentication()).isNull();
assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId);
assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Mock Clone Instance #spring-security_MCI_31
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
- Test Case Count: 18
- MO Count: 18
Reusable Method
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_31_1
Test Case Name: convertWhenSamlResponseThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseThenToken() {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseThenToken() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_2
Test Case Name: convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_3
Test Case Name: convertWhenGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestThenInflates() {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestThenInflates() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_4
Test Case Name: convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_5
Test Case Name: convertWhenUsingSamlUtilsBase64ThenXmlIsValid(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_6
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- converter.setAuthenticationRequestRepository(authenticationRequestRepository);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
+ converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_7
Test Case Name: convertWhenSamlResponseThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseThenToken() {
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseThenToken() {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_8
Test Case Name: convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_9
Test Case Name: convertWhenGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestThenInflates() {
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestThenInflates() {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_10
Test Case Name: convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_11
Test Case Name: convertWhenUsingSamlUtilsBase64ThenXmlIsValid(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_12
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
- OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
- converter.setAuthenticationRequestRepository(authenticationRequestRepository);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
+ AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
+ given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
+ converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_13
Test Case Name: convertWhenSamlResponseThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseThenToken() {
- OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseThenToken() {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_14
Test Case Name: convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
- OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withCauseInstanceOf(IllegalArgumentException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_15
Test Case Name: convertWhenGetRequestThenInflates(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestThenInflates() {
- OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestThenInflates() {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_16
Test Case Name: convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
- OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)).withRootCauseInstanceOf(IOException.class).satisfies((ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE)).satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_17
Test Case Name: convertWhenUsingSamlUtilsBase64ThenXmlIsValid(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
- OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(this.registration);
+ OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_31_18
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findByRegistrationId(any())).willReturn(registration);
return registrations;
}
}
Mock Clone Instance #spring-security_MCI_32
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_32_1
Test Case Name: convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
Original Test Code (click to expand)
@Test
public void convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId() {
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
String response = serialize(signed(response()));
String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_32_2
Test Case Name: convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
public void convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId() {
- OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
- String response = serialize(signed(response()));
- String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(
+ TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
+ OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
+ String response = serialize(signed(response()));
+ String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
String response = serialize(signed(response()));
String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Test Case ID #spring-security_Test_32_3
Test Case Name: convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: registrations
Suggested Diff
@@
String response = serialize(signed(response()));
String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
- given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
+ this.registrations = MockRelyingPartyRegistrationRepository.createMockRelyingPartyRegistrationRepository(
+ TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID, this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId() {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
String response = serialize(signed(response()));
String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationRepository {
public static RelyingPartyRegistrationRepository createMockRelyingPartyRegistrationRepository(String assertingPartyEntityId, RelyingPartyRegistration registration) {
RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class);
given(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).willReturn(registration);
return registrations;
}
}
Mock Clone Instance #spring-security_MCI_33
- Scope: method level
- Mocked Class:
javax.naming.ldap.Control
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Control createMockControl(String idReturn) {
Control control = mock(Control.class);
given(control.getID()).willReturn(idReturn);
return control;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_33_1
Test Case Name: returnsNullForUnrecognisedOID(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\ppolicy\PasswordPolicyControlFactoryTests.java)
Mock Object Variable Name: wrongCtrl
Suggested Diff
@@
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
- Control wrongCtrl = mock(Control.class);
- given(wrongCtrl.getID()).willReturn("wrongId");
+ Control wrongCtrl = createMockControl("wrongId");
assertThat(ctrlFactory.getControlInstance(wrongCtrl)).isNull();
@@
Original Test Code (click to expand)
@Test
public void returnsNullForUnrecognisedOID() {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control wrongCtrl = mock(Control.class);
given(wrongCtrl.getID()).willReturn("wrongId");
assertThat(ctrlFactory.getControlInstance(wrongCtrl)).isNull();
}
Reusable Method for MCI (click to expand)
private static Control createMockControl(String idReturn) {
Control control = mock(Control.class);
given(control.getID()).willReturn(idReturn);
return control;
}
Test Case ID #spring-security_Test_33_2
Test Case Name: returnsControlForCorrectOID(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\ppolicy\PasswordPolicyControlFactoryTests.java)
Mock Object Variable Name: control
Suggested Diff
@@
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
- Control control = mock(Control.class);
- given(control.getID()).willReturn(PasswordPolicyControl.OID);
- given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
+ Control control = createMockControl(PasswordPolicyControl.OID);
+ given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertThat(result).isNotNull();
assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue());
@@
Original Test Code (click to expand)
@Test
public void returnsControlForCorrectOID() {
PasswordPolicyControlFactory ctrlFactory = new PasswordPolicyControlFactory();
Control control = mock(Control.class);
given(control.getID()).willReturn(PasswordPolicyControl.OID);
given(control.getEncodedValue()).willReturn(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL);
Control result = ctrlFactory.getControlInstance(control);
assertThat(result).isNotNull();
assertThat(PasswordPolicyResponseControlTests.OPENLDAP_LOCKED_CTRL).isEqualTo(result.getEncodedValue());
}
Reusable Method for MCI (click to expand)
private static Control createMockControl(String idReturn) {
Control control = mock(Control.class);
given(control.getID()).willReturn(idReturn);
return control;
}
Mock Clone Instance #spring-security_MCI_34
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.ReactiveAuthorizationManager<org.springframework.security.authorization.method.MethodInvocationResult>
- Test Case Count: 5
- MO Count: 5
Reusable Method
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_34_1
Test Case Name: invokeMonoWhenMockReactiveAuthorizationManagerThenVerify(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManagerWithAuthorizeRealMethod();
+ given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john");
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenMockReactiveAuthorizationManagerThenVerify() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john");
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_34_2
Test Case Name: invokeFluxWhenMockReactiveAuthorizationManagerThenVerify(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManagerWithAuthorizeRealMethod();
+ given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenMockReactiveAuthorizationManagerThenVerify() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(true)));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_34_3
Test Case Name: invokeWhenMockReactiveAuthorizationManagerDeniedThenAccessDeniedException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(false)));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManagerWithAuthorizeRealMethod();
+ given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(false)));
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeWhenMockReactiveAuthorizationManagerDeniedThenAccessDeniedException() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.just(new AuthorizationDecision(false)));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_34_4
Test Case Name: invokeMonoWhenEmptyDecisionThenUseDefaultPostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManagerWithAuthorizeRealMethod();
+ given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AuthorizationDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenEmptyDecisionThenUseDefaultPostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AuthorizationDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_34_5
Test Case Name: invokeWhenCustomAuthorizationDeniedExceptionThenThrows(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: manager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Mono.just("ok"));
- ReactiveAuthorizationManager<MethodInvocationResult> manager = mock(ReactiveAuthorizationManager.class);
- given(manager.check(any(), any())).willReturn(Mono.error(new MyAuthzDeniedException("denied", new AuthorizationDecision(false))));
- given(manager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocationResult> manager = createMockReactiveAuthorizationManagerWithAuthorizeRealMethod();
+ given(manager.check(any(), any())).willReturn(Mono.error(new MyAuthzDeniedException("denied", new AuthorizationDecision(false))));
AuthorizationManagerAfterReactiveMethodInterceptor advice = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> ((Mono<?>) advice.invoke(mockMethodInvocation)).block());
@@
Original Test Code (click to expand)
@Test
public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("ok"));
ReactiveAuthorizationManager<MethodInvocationResult> manager = mock(ReactiveAuthorizationManager.class);
given(manager.check(any(), any())).willReturn(Mono.error(new MyAuthzDeniedException("denied", new AuthorizationDecision(false))));
given(manager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor advice = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> ((Mono<?>) advice.invoke(mockMethodInvocation)).block());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocationResult> createMockReactiveAuthorizationManagerWithAuthorizeRealMethod() {
ReactiveAuthorizationManager<MethodInvocationResult> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_35
- Scope: method level
- Mocked Class:
org.springframework.security.web.RedirectStrategy
- Test Case Count: 4
- MO Count: 4
Reusable Method
private RedirectStrategy redirect;
@BeforeEach
public void setUp() {
redirect = mock(RedirectStrategy.class);
}
redirect
The refactoring details in each test cases
Test Case ID #spring-security_Test_35_1
Test Case Name: doFilterWhenNoSessionThenChainIsContinued(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: redirect
Suggested Diff
@@
@Test
public void doFilterWhenNoSessionThenChainIsContinued() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- RedirectStrategy redirect = mock(RedirectStrategy.class);
+ // removed local mock; replaced with global field `redirect`
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNoSessionThenChainIsContinued() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
Reusable Method for MCI (click to expand)
private RedirectStrategy redirect;
@BeforeEach
public void setUp() {
redirect = mock(RedirectStrategy.class);
}
redirect
Test Case ID #spring-security_Test_35_2
Mock Object Variable Name: redirect
Suggested Diff
@@
@Test
public void doFilterWhenNoSessionInformationThenChainIsContinued() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockHttpSession());
MockHttpServletResponse response = new MockHttpServletResponse();
- RedirectStrategy redirect = mock(RedirectStrategy.class);
+ // removed local mock; replaced with global field `redirect`
SessionRegistry registry = mock(SessionRegistry.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNoSessionInformationThenChainIsContinued() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockHttpSession());
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
Reusable Method for MCI (click to expand)
private RedirectStrategy redirect;
@BeforeEach
public void setUp() {
redirect = mock(RedirectStrategy.class);
}
redirect
Test Case ID #spring-security_Test_35_3
Test Case Name: doFilterWhenCustomRedirectStrategyThenCustomRedirectStrategyUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: redirect
Suggested Diff
@@
@Test
public void doFilterWhenCustomRedirectStrategyThenCustomRedirectStrategyUsed() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
- RedirectStrategy redirect = mock(RedirectStrategy.class);
+ // removed local mock; replaced with global field `redirect`
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl);
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
- verify(redirect).sendRedirect(request, response, expiredUrl);
+ verify(redirect).sendRedirect(request, response, expiredUrl);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomRedirectStrategyThenCustomRedirectStrategyUsed() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl);
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
verify(redirect).sendRedirect(request, response, expiredUrl);
}
Reusable Method for MCI (click to expand)
private RedirectStrategy redirect;
@BeforeEach
public void setUp() {
redirect = mock(RedirectStrategy.class);
}
redirect
Test Case ID #spring-security_Test_35_4
Test Case Name: doFilterWhenOverrideThenCustomRedirectStrategyUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: redirect
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
- RedirectStrategy redirect = mock(RedirectStrategy.class);
+ // removed local mock; replaced with global field `redirect`
final String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl + "will-be-overrridden") {
@Override
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return expiredUrl;
}
};
- filter.setRedirectStrategy(redirect);
+ filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
- verify(redirect).sendRedirect(request, response, expiredUrl);
+ verify(redirect).sendRedirect(request, response, expiredUrl);
Original Test Code (click to expand)
@Test
public void doFilterWhenOverrideThenCustomRedirectStrategyUsed() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
final String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(mockSessionRegistry(), expiredUrl + "will-be-overrridden") {
@Override
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return expiredUrl;
}
};
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
verify(redirect).sendRedirect(request, response, expiredUrl);
}
Reusable Method for MCI (click to expand)
private RedirectStrategy redirect;
@BeforeEach
public void setUp() {
redirect = mock(RedirectStrategy.class);
}
redirect
Mock Clone Instance #spring-security_MCI_36
- Scope: method level
- Mocked Class:
org.springframework.web.server.ServerWebExchange
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServerWebExchange createMockServerWebExchange(Mono<?> sessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(sessionMono);
return exchange;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_36_1
Test Case Name: saveAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\WebSessionServerOAuth2AuthorizedClientRepositoryTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
@Test
public void saveAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException() {
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getSession()).willReturn(Mono.empty());
+ ServerWebExchange exchange = createMockServerWebExchange(Mono.empty());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1, mock(OAuth2AccessToken.class));
// @formatter:off
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, exchange).block()).withMessage("session cannot be null");
// @formatter:on
}
@@
Original Test Code (click to expand)
@Test
public void saveAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException() {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(Mono.empty());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1, mock(OAuth2AccessToken.class));
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, exchange).block()).withMessage("session cannot be null");
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Mono<?> sessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(sessionMono);
return exchange;
}
Test Case ID #spring-security_Test_36_2
Test Case Name: removeAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\WebSessionServerOAuth2AuthorizedClientRepositoryTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
@Test
public void removeAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException() {
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getSession()).willReturn(Mono.empty());
+ ServerWebExchange exchange = createMockServerWebExchange(Mono.empty());
// @formatter:off
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, exchange).block()).withMessage("session cannot be null");
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void removeAuthorizedClientWhenSessionIsNullThenThrowIllegalArgumentException() {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(Mono.empty());
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, exchange).block()).withMessage("session cannot be null");
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Mono<?> sessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(sessionMono);
return exchange;
}
Mock Clone Instance #spring-security_MCI_37
- Scope: method level
- Mocked Class:
org.springframework.web.server.ServerWebExchange
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServerWebExchange createMockServerWebExchange(Mono<WebSession> webSessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(webSessionMono);
return exchange;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_37_1
Test Case Name: loadWhenCacheSecurityContextThenSubscribeOnce(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\context\WebSessionServerSecurityContextRepositoryTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
PublisherProbe<WebSession> webSession = PublisherProbe.empty();
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getSession()).willReturn(webSession.mono());
+ ServerWebExchange exchange = createMockServerWebExchange(webSession.mono());
this.repository.setCacheSecurityContext(true);
Mono<SecurityContext> context = this.repository.load(exchange);
assertThat(context.block()).isSameAs(context.block());
assertThat(webSession.subscribeCount()).isEqualTo(1);
}
Original Test Code (click to expand)
@Test
public void loadWhenCacheSecurityContextThenSubscribeOnce() {
PublisherProbe<WebSession> webSession = PublisherProbe.empty();
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(webSession.mono());
this.repository.setCacheSecurityContext(true);
Mono<SecurityContext> context = this.repository.load(exchange);
assertThat(context.block()).isSameAs(context.block());
assertThat(webSession.subscribeCount()).isEqualTo(1);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Mono<WebSession> webSessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(webSessionMono);
return exchange;
}
Test Case ID #spring-security_Test_37_2
Test Case Name: loadWhenNotCacheSecurityContextThenSubscribeMultiple(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\context\WebSessionServerSecurityContextRepositoryTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
PublisherProbe<WebSession> webSession = PublisherProbe.empty();
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getSession()).willReturn(webSession.mono());
+ ServerWebExchange exchange = createMockServerWebExchange(webSession.mono());
Mono<SecurityContext> context = this.repository.load(exchange);
assertThat(context.block()).isSameAs(context.block());
assertThat(webSession.subscribeCount()).isEqualTo(2);
}
Original Test Code (click to expand)
@Test
public void loadWhenNotCacheSecurityContextThenSubscribeMultiple() {
PublisherProbe<WebSession> webSession = PublisherProbe.empty();
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(webSession.mono());
Mono<SecurityContext> context = this.repository.load(exchange);
assertThat(context.block()).isSameAs(context.block());
assertThat(webSession.subscribeCount()).isEqualTo(2);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Mono<WebSession> webSessionMono) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getSession()).willReturn(webSessionMono);
return exchange;
}
Mock Clone Instance #spring-security_MCI_38
- Scope: method level
- Mocked Class:
org.springframework.web.server.ServerWebExchange
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static ServerWebExchange createMockServerWebExchange(Authentication principal) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(principal));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
return exchange;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_38_1
Test Case Name: handleWhenNotOAuth2AuthenticatedThenStatus403(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
Authentication token = new TestingAuthenticationToken("user", "pass");
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getPrincipal()).willReturn(Mono.just(token));
- given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
+ ServerWebExchange exchange = createMockServerWebExchange(token);
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer"));
@@
Original Test Code (click to expand)
@Test
public void handleWhenNotOAuth2AuthenticatedThenStatus403() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer"));
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Authentication principal) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(principal));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
return exchange;
}
Test Case ID #spring-security_Test_38_2
Test Case Name: handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
Authentication token = new TestingAuthenticationToken("user", "pass");
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getPrincipal()).willReturn(Mono.just(token));
- given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
+ ServerWebExchange exchange = createMockServerWebExchange(token);
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer realm=\"test\""));
@@
Original Test Code (click to expand)
@Test
public void handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer realm=\"test\""));
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Authentication principal) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(principal));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
return exchange;
}
Test Case ID #spring-security_Test_38_3
Test Case Name: handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\web\access\server\BearerTokenServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: exchange
Suggested Diff
@@
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
- ServerWebExchange exchange = mock(ServerWebExchange.class);
- given(exchange.getPrincipal()).willReturn(Mono.just(token));
- given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
+ ServerWebExchange exchange = createMockServerWebExchange(token);
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
// @formatter:off
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\""));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute() {
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\""));
}
Reusable Method for MCI (click to expand)
private static ServerWebExchange createMockServerWebExchange(Authentication principal) {
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(principal));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
return exchange;
}
Mock Clone Instance #spring-security_MCI_39
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.authentication.ServerAuthenticationConverter
- Test Case Count: 5
- MO Count: 5
Reusable Method
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_39_1
Test Case Name: matchesWhenNotEmptyThenReturnTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationConverterServerWebExchangeMatcherTests.java)
Mock Object Variable Name: converter
Suggested Diff
@@
@Test
public void matchesWhenNotEmptyThenReturnTrue() {
- given(this.converter.convert(any())).willReturn(Mono.just(this.authentication));
+ this.converter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(this.authentication);
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesWhenNotEmptyThenReturnTrue() {
given(this.converter.convert(any())).willReturn(Mono.just(this.authentication));
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
Test Case ID #spring-security_Test_39_2
Test Case Name: filterWhenConvertAndAuthenticationSuccessThenSuccess(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
- given(this.authenticationConverter.convert(any())).willReturn(authentication);
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(authentication.block());
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
given(this.successHandler.onAuthenticationSuccess(any(), any())).willReturn(Mono.empty());
given(this.securityContextRepository.save(any(), any())).willAnswer((a) -> Mono.just(a.getArguments()[0]));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty();
verify(this.successHandler).onAuthenticationSuccess(any(), eq(authentication.block()));
verify(this.securityContextRepository).save(any(), any());
verifyNoMoreInteractions(this.failureHandler);
@@
Original Test Code (click to expand)
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
given(this.successHandler.onAuthenticationSuccess(any(), any())).willReturn(Mono.empty());
given(this.securityContextRepository.save(any(), any())).willAnswer((a) -> Mono.just(a.getArguments()[0]));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty();
verify(this.successHandler).onAuthenticationSuccess(any(), eq(authentication.block()));
verify(this.securityContextRepository).save(any(), any());
verifyNoMoreInteractions(this.failureHandler);
}
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
Test Case ID #spring-security_Test_39_3
Test Case Name: filterWhenConvertAndAuthenticationEmptyThenServerError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
- given(this.authenticationConverter.convert(any())).willReturn(authentication);
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(authentication.block());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
Original Test Code (click to expand)
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.successHandler, this.failureHandler);
}
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
Test Case ID #spring-security_Test_39_4
Test Case Name: filterWhenConvertAndAuthenticationFailThenEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
- given(this.authenticationConverter.convert(any())).willReturn(authentication);
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(authentication.block());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Failed")));
given(this.failureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty();
verify(this.failureHandler).onAuthenticationFailure(any(), any());
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.successHandler);
@@
Original Test Code (click to expand)
@Test
public void filterWhenConvertAndAuthenticationFailThenEntryPoint() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Failed")));
given(this.failureHandler.onAuthenticationFailure(any(), any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody().isEmpty();
verify(this.failureHandler).onAuthenticationFailure(any(), any());
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.successHandler);
}
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
Test Case ID #spring-security_Test_39_5
Test Case Name: filterWhenConvertAndAuthenticationExceptionThenServerError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
- given(this.authenticationConverter.convert(any())).willReturn(authentication);
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(authentication.block());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new RuntimeException("Failed")));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
Original Test Code (click to expand)
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
@Test
public void filterWhenConvertAndAuthenticationExceptionThenServerError() {
Mono<Authentication> authentication = Mono.just(new TestingAuthenticationToken("test", "this", "ROLE_USER"));
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new RuntimeException("Failed")));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.successHandler, this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Authentication authentication) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(Mono.just(authentication));
return converter;
}
}
Mock Clone Instance #spring-security_MCI_40
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.authentication.ServerAuthenticationConverter
- Test Case Count: 4
- MO Count: 4
Reusable Method
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Mono<?> convertReturn) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(convertReturn);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_40_1
Test Case Name: matchesWhenEmptyThenReturnFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationConverterServerWebExchangeMatcherTests.java)
Mock Object Variable Name: converter
Suggested Diff
@@
@Test
public void matchesWhenEmptyThenReturnFalse() {
- given(this.converter.convert(any())).willReturn(Mono.empty());
+ this.converter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(Mono.empty());
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesWhenEmptyThenReturnFalse() {
given(this.converter.convert(any())).willReturn(Mono.empty());
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Mono<?> convertReturn) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(convertReturn);
return converter;
}
}
Test Case ID #spring-security_Test_40_2
Test Case Name: matchesWhenErrorThenReturnFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationConverterServerWebExchangeMatcherTests.java)
Mock Object Variable Name: converter
Suggested Diff
@@
@Test
public void matchesWhenErrorThenReturnFalse() {
- given(this.converter.convert(any())).willReturn(Mono.error(new RuntimeException()));
+ this.converter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(Mono.error(new RuntimeException()));
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesWhenErrorThenReturnFalse() {
given(this.converter.convert(any())).willReturn(Mono.error(new RuntimeException()));
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Mono<?> convertReturn) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(convertReturn);
return converter;
}
}
Test Case ID #spring-security_Test_40_3
Test Case Name: filterWhenConvertEmptyThenOk(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
@Test
public void filterWhenConvertEmptyThenOk() {
- given(this.authenticationConverter.convert(any())).willReturn(Mono.empty());
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler);
}
@@
Original Test Code (click to expand)
@Test
public void filterWhenConvertEmptyThenOk() {
given(this.authenticationConverter.convert(any())).willReturn(Mono.empty());
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler);
}
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Mono<?> convertReturn) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(convertReturn);
return converter;
}
}
Test Case ID #spring-security_Test_40_4
Test Case Name: filterWhenConvertErrorThenServerError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\AuthenticationWebFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
- this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
@Test
public void filterWhenConvertErrorThenServerError() {
- given(this.authenticationConverter.convert(any())).willReturn(Mono.error(new RuntimeException("Unexpected")));
+ this.authenticationConverter = MockServerAuthenticationConverter.createMockServerAuthenticationConverter(Mono.error(new RuntimeException("Unexpected")));
+ this.filter.setServerAuthenticationConverter(this.authenticationConverter);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler);
}
Original Test Code (click to expand)
@BeforeEach
public void setup() {
this.filter = new AuthenticationWebFilter(this.authenticationManager);
this.filter.setAuthenticationSuccessHandler(this.successHandler);
this.filter.setServerAuthenticationConverter(this.authenticationConverter);
this.filter.setSecurityContextRepository(this.securityContextRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
}
@Test
public void filterWhenConvertErrorThenServerError() {
given(this.authenticationConverter.convert(any())).willReturn(Mono.error(new RuntimeException("Unexpected")));
WebTestClient client = WebTestClientBuilder.bindToWebFilters(this.filter).build();
client.get().uri("/").exchange().expectStatus().is5xxServerError().expectBody().isEmpty();
verify(this.securityContextRepository, never()).save(any(), any());
verifyNoMoreInteractions(this.authenticationManager, this.successHandler, this.failureHandler);
}
Reusable Method for MCI (click to expand)
public class MockServerAuthenticationConverter {
public static ServerAuthenticationConverter createMockServerAuthenticationConverter(Mono<?> convertReturn) {
ServerAuthenticationConverter converter = mock(ServerAuthenticationConverter.class);
given(converter.convert(any())).willReturn(convertReturn);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_41
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<jakarta.servlet.http.HttpServletRequest, java.lang.String>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String convertReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(convertReturn);
return relayState;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_41_1
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutRequestResolverTests.java)
Mock Object Variable Name: relayState
Suggested Diff
@@
given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration);
- Converter<HttpServletRequest, String> relayState = mock(Converter.class);
- given(relayState.convert(any())).willReturn("any-state");
+ Converter<HttpServletRequest, String> relayState = MockConverter.createMockRelayState("any-state");
this.logoutRequestResolver.setRelayStateResolver(relayState);
Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication());
assertThat(logoutRequest.getRelayState()).isEqualTo("any-state");
verify(relayState).convert(any());
}
Original Test Code (click to expand)
@Test
public void resolveWhenCustomRelayStateThenUses() {
given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("any-state");
this.logoutRequestResolver.setRelayStateResolver(relayState);
Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication());
assertThat(logoutRequest.getRelayState()).isEqualTo("any-state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String convertReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(convertReturn);
return relayState;
}
}
Test Case ID #spring-security_Test_41_2
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolverTests.java)
Mock Object Variable Name: relayState
Suggested Diff
@@
given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration);
- Converter<HttpServletRequest, String> relayState = mock(Converter.class);
- given(relayState.convert(any())).willReturn("any-state");
+ Converter<HttpServletRequest, String> relayState = MockConverter.createMockRelayState("any-state");
this.logoutRequestResolver.setRelayStateResolver(relayState);
Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication());
assertThat(logoutRequest.getRelayState()).isEqualTo("any-state");
verify(relayState).convert(any());
Original Test Code (click to expand)
@Test
public void resolveWhenCustomRelayStateThenUses() {
given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("any-state");
this.logoutRequestResolver.setRelayStateResolver(relayState);
Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication());
assertThat(logoutRequest.getRelayState()).isEqualTo("any-state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String convertReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(convertReturn);
return relayState;
}
}
Mock Clone Instance #spring-security_MCI_42
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<jakarta.servlet.http.HttpServletRequest, java.lang.String>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String relayStateReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(relayStateReturn);
return relayState;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_42_1
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml4AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relayState
Suggested Diff
@@
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
- Converter<HttpServletRequest, String> relayState = mock(Converter.class);
- given(relayState.convert(any())).willReturn("state");
+ Converter<HttpServletRequest, String> relayState = MockConverter.createMockRelayState("state");
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
@@
Original Test Code (click to expand)
@Test
void resolveWhenCustomRelayStateThenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String relayStateReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(relayStateReturn);
return relayState;
}
}
Test Case ID #spring-security_Test_42_2
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relayState
Suggested Diff
@@
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
- Converter<HttpServletRequest, String> relayState = mock(Converter.class);
- given(relayState.convert(any())).willReturn("state");
+ Converter<HttpServletRequest, String> relayState = MockConverter.createMockRelayState("state");
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
@@
Original Test Code (click to expand)
@Test
void resolveWhenCustomRelayStateThenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<HttpServletRequest, String> createMockRelayState(String relayStateReturn) {
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn(relayStateReturn);
return relayState;
}
}
Mock Clone Instance #spring-security_MCI_43
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockParametersConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2RefreshTokenGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_43_1
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientRefreshTokenTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2RefreshTokenGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_43_2
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientRefreshTokenTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken, scopes);
- Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue()), param(OAuth2ParameterNames.REFRESH_TOKEN, this.refreshToken.getTokenValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
Set<String> scopes = clientRegistration.getScopes();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken, scopes);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue()), param(OAuth2ParameterNames.REFRESH_TOKEN, this.refreshToken.getTokenValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2RefreshTokenGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_43_3
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveRefreshTokenTokenResponseClientTests.java)
Mock Object Variable Name: addedParametersConverter
Suggested Diff
@@
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(addedParametersConverter.convert(request)).willReturn(parameters);
+ Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> addedParametersConverter = MockParametersConverter.createMockParametersConverter(request, parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=refresh_token", "custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2RefreshTokenGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_43_4
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveRefreshTokenTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(request)).willReturn(parameters);
+ Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(request, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2RefreshTokenGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2RefreshTokenGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Mock Clone Instance #spring-security_MCI_44
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.ReactiveAuthorizationManager<org.springframework.security.rsocket.util.matcher.PayloadExchangeAuthorizationContext>
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> createMockReactiveAuthorizationManager(Mono<AuthorizationDecision> checkReturn) {
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> mock = mock(ReactiveAuthorizationManager.class);
given(mock.check(any(), any())).willReturn(checkReturn);
return mock;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_44_1
Test Case Name: checkWhenGrantedThenGranted(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\authorization\PayloadExchangeMatcherReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authz
Suggested Diff
@@
@Test
public void checkWhenGrantedThenGranted() {
AuthorizationDecision expected = new AuthorizationDecision(true);
- given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
+ this.authz = createMockReactiveAuthorizationManager(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Original Test Code (click to expand)
@Test
public void checkWhenGrantedThenGranted() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> createMockReactiveAuthorizationManager(Mono<AuthorizationDecision> checkReturn) {
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> mock = mock(ReactiveAuthorizationManager.class);
given(mock.check(any(), any())).willReturn(checkReturn);
return mock;
}
Test Case ID #spring-security_Test_44_2
Test Case Name: checkWhenDeniedThenDenied(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\authorization\PayloadExchangeMatcherReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authz
Suggested Diff
@@
public void checkWhenDeniedThenDenied() {
AuthorizationDecision expected = new AuthorizationDecision(false);
- given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
+ this.authz = createMockReactiveAuthorizationManager(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Original Test Code (click to expand)
@Test
public void checkWhenDeniedThenDenied() {
AuthorizationDecision expected = new AuthorizationDecision(false);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> createMockReactiveAuthorizationManager(Mono<AuthorizationDecision> checkReturn) {
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> mock = mock(ReactiveAuthorizationManager.class);
given(mock.check(any(), any())).willReturn(checkReturn);
return mock;
}
Test Case ID #spring-security_Test_44_3
Test Case Name: checkWhenFirstMatchThenSecondUsed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\authorization\PayloadExchangeMatcherReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authz
Suggested Diff
@@
@Test
public void checkWhenFirstMatchThenSecondUsed() {
- AuthorizationDecision expected = new AuthorizationDecision(true);
- given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
+ AuthorizationDecision expected = new AuthorizationDecision(true);
+ this.authz = createMockReactiveAuthorizationManager(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz2)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Original Test Code (click to expand)
@Test
public void checkWhenFirstMatchThenSecondUsed() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz)).add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz2)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> createMockReactiveAuthorizationManager(Mono<AuthorizationDecision> checkReturn) {
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> mock = mock(ReactiveAuthorizationManager.class);
given(mock.check(any(), any())).willReturn(checkReturn);
return mock;
}
Test Case ID #spring-security_Test_44_4
Test Case Name: checkWhenSecondMatchThenSecondUsed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\authorization\PayloadExchangeMatcherReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authz2
Suggested Diff
@@
@Test
public void checkWhenSecondMatchThenSecondUsed() {
AuthorizationDecision expected = new AuthorizationDecision(true);
- given(this.authz2.check(any(), any())).willReturn(Mono.just(expected));
+ this.authz2 = createMockReactiveAuthorizationManager(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz)).add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz2)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
@@
Original Test Code (click to expand)
@Test
public void checkWhenSecondMatchThenSecondUsed() {
AuthorizationDecision expected = new AuthorizationDecision(true);
given(this.authz2.check(any(), any())).willReturn(Mono.just(expected));
PayloadExchangeMatcherReactiveAuthorizationManager manager = PayloadExchangeMatcherReactiveAuthorizationManager.builder().add(new PayloadExchangeMatcherEntry<>((e) -> PayloadExchangeMatcher.MatchResult.notMatch(), this.authz)).add(new PayloadExchangeMatcherEntry<>(PayloadExchangeMatchers.anyExchange(), this.authz2)).build();
assertThat(manager.check(Mono.empty(), this.exchange).block()).isEqualTo(expected);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> createMockReactiveAuthorizationManager(Mono<AuthorizationDecision> checkReturn) {
ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext> mock = mock(ReactiveAuthorizationManager.class);
given(mock.check(any(), any())).willReturn(checkReturn);
return mock;
}
Mock Clone Instance #spring-security_MCI_45
- Scope: method level
- Mocked Class:
org.springframework.security.ldap.authentication.LdapAuthenticator
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static LdapAuthenticator createMockLdapAuthenticator(UsernamePasswordAuthenticationToken token, UsernameNotFoundException exception) {
LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
given(authenticator.authenticate(token)).willThrow(exception);
return authenticator;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_45_1
Test Case Name: usernameNotFoundExceptionIsHiddenByDefault(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\authentication\LdapAuthenticationProviderTests.java)
Mock Object Variable Name: authenticator
Suggested Diff
@@
public void usernameNotFoundExceptionIsHiddenByDefault() {
- final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
- given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
+ final LdapAuthenticator authenticator = createMockLdapAuthenticator(joe, new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe));
}
Original Test Code (click to expand)
@Test
public void usernameNotFoundExceptionIsHiddenByDefault() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(joe));
}
Reusable Method for MCI (click to expand)
private static LdapAuthenticator createMockLdapAuthenticator(UsernamePasswordAuthenticationToken token, UsernameNotFoundException exception) {
LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
given(authenticator.authenticate(token)).willThrow(exception);
return authenticator;
}
Test Case ID #spring-security_Test_45_2
Mock Object Variable Name: authenticator
Suggested Diff
@@
@Test
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
- final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
- given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
+ final LdapAuthenticator authenticator = createMockLdapAuthenticator(joe, new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false);
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(joe));
}
@@
Original Test Code (click to expand)
@Test
public void usernameNotFoundExceptionIsNotHiddenIfConfigured() {
final LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
final UsernamePasswordAuthenticationToken joe = UsernamePasswordAuthenticationToken.unauthenticated("joe", "password");
given(authenticator.authenticate(joe)).willThrow(new UsernameNotFoundException("nobody"));
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setHideUserNotFoundExceptions(false);
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(joe));
}
Reusable Method for MCI (click to expand)
private static LdapAuthenticator createMockLdapAuthenticator(UsernamePasswordAuthenticationToken token, UsernameNotFoundException exception) {
LdapAuthenticator authenticator = mock(LdapAuthenticator.class);
given(authenticator.authenticate(token)).willThrow(exception);
return authenticator;
}
Mock Clone Instance #spring-security_MCI_46
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<java.util.Map<java.lang.String, java.lang.Object>, java.util.Map<java.lang.String, java.lang.Object>>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter(Map<String, String> returnMap) {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willReturn(returnMap);
return claimSetConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_46_1
Test Case Name: decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: claimSetConverter
Suggested Diff
@@
@Test
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
- Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
- given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
+ Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MockClaimSetConverter.createMockClaimSetConverter(Collections.singletonMap("custom", "value"));
this.jwtDecoder.setClaimSetConverter(claimSetConverter);
Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims()).containsEntry("custom", "value");
}
Original Test Code (click to expand)
@Test
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
this.jwtDecoder.setClaimSetConverter(claimSetConverter);
Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims()).containsEntry("custom", "value");
}
Reusable Method for MCI (click to expand)
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter(Map<String, String> returnMap) {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willReturn(returnMap);
return claimSetConverter;
}
}
Test Case ID #spring-security_Test_46_2
Test Case Name: decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: claimSetConverter
Suggested Diff
@@
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
- Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
+ Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MockClaimSetConverter.createMockClaimSetConverter(Collections.singletonMap("custom", "value"));
this.decoder.setClaimSetConverter(claimSetConverter);
- given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims()).containsEntry("custom", "value");
verify(claimSetConverter).convert(any(Map.class));
@@
Original Test Code (click to expand)
@Test
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.decoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims()).containsEntry("custom", "value");
verify(claimSetConverter).convert(any(Map.class));
}
Reusable Method for MCI (click to expand)
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter(Map<String, String> returnMap) {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willReturn(returnMap);
return claimSetConverter;
}
}
Mock Clone Instance #spring-security_MCI_47
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<java.util.Map<java.lang.String, java.lang.Object>, java.util.Map<java.lang.String, java.lang.Object>>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
return claimSetConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_47_1
Test Case Name: decodeWhenClaimSetConverterFailsThenBadJwtException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: claimSetConverter
Suggested Diff
@@
// gh-7885
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
- Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
- this.jwtDecoder.setClaimSetConverter(claimSetConverter);
- given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
+ Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MockClaimSetConverter.createMockClaimSetConverter();
+ this.jwtDecoder.setClaimSetConverter(claimSetConverter);
// @formatter:off
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT));
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.jwtDecoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT));
}
Reusable Method for MCI (click to expand)
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
return claimSetConverter;
}
}
Test Case ID #spring-security_Test_47_2
Test Case Name: decodeWhenClaimSetConverterFailsThenBadJwtException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: claimSetConverter
Suggested Diff
@@
// gh-7885
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
- Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
- this.decoder.setClaimSetConverter(claimSetConverter);
- given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
+ Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MockClaimSetConverter.createMockClaimSetConverter();
+ this.decoder.setClaimSetConverter(claimSetConverter);
// @formatter:off
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode(this.messageReadToken).block());
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.decoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder.decode(this.messageReadToken).block());
}
Reusable Method for MCI (click to expand)
public class MockClaimSetConverter {
public static Converter<Map<String, Object>, Map<String, Object>> createMockClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
return claimSetConverter;
}
}
Mock Clone Instance #spring-security_MCI_48
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest
- Test Case Count: 2
- MO Count: 5
Reusable Method
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_48_1
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequest
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
+ AbstractSaml2AuthenticationRequest authenticationRequest = MockAbstractSaml2AuthenticationRequest.createMockAbstractSaml2AuthenticationRequest(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
Test Case ID #spring-security_Test_48_2
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequest
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
+ AbstractSaml2AuthenticationRequest authenticationRequest = MockAbstractSaml2AuthenticationRequest.createMockAbstractSaml2AuthenticationRequest(this.registration.getRegistrationId());
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
Test Case ID #spring-security_Test_48_3
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequest
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
+ AbstractSaml2AuthenticationRequest authenticationRequest = MockAbstractSaml2AuthenticationRequest.createMockAbstractSaml2AuthenticationRequest(this.registration.getRegistrationId());
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
Test Case ID #spring-security_Test_48_4
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequest
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
+ AbstractSaml2AuthenticationRequest authenticationRequest = MockAbstractSaml2AuthenticationRequest.createMockAbstractSaml2AuthenticationRequest(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
Test Case ID #spring-security_Test_48_5
Test Case Name: convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequest
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
+ AbstractSaml2AuthenticationRequest authenticationRequest = MockAbstractSaml2AuthenticationRequest.createMockAbstractSaml2AuthenticationRequest(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
verify(resolver).resolve(any(), eq(this.relyingPartyRegistration.getRegistrationId()));
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver(@Mock RelyingPartyRegistrationResolver resolver) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
verify(resolver).resolve(any(), eq(this.relyingPartyRegistration.getRegistrationId()));
}
Reusable Method for MCI (click to expand)
public class MockAbstractSaml2AuthenticationRequest {
public static AbstractSaml2AuthenticationRequest createMockAbstractSaml2AuthenticationRequest(String relyingPartyRegistrationId) {
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(relyingPartyRegistrationId);
return authenticationRequest;
}
}
Mock Clone Instance #spring-security_MCI_49
- Scope: method level
- Mocked Class:
org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AbstractSaml2AuthenticationRequest createMockAuthenticationRequest(String authenticationRequestUri) {
AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(authenticationRequestUri);
return mockAuthenticationRequest;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_49_1
Test Case Name: loadAuthenticationRequestWhenAttributeInSessionThenReturnsAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\servlet\HttpSessionSaml2AuthenticationRequestRepositoryTests.java)
Mock Object Variable Name: mockAuthenticationRequest
Suggested Diff
@@
public void loadAuthenticationRequestWhenAttributeInSessionThenReturnsAuthenticationRequest() {
- AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL);
+ AbstractSaml2AuthenticationRequest mockAuthenticationRequest = createMockAuthenticationRequest(IDP_SSO_URL);
this.request.getSession();
this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository.loadAuthenticationRequest(this.request);
assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL);
}
Original Test Code (click to expand)
@Test
public void loadAuthenticationRequestWhenAttributeInSessionThenReturnsAuthenticationRequest() {
AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL);
this.request.getSession();
this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository.loadAuthenticationRequest(this.request);
assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL);
}
Reusable Method for MCI (click to expand)
private static AbstractSaml2AuthenticationRequest createMockAuthenticationRequest(String authenticationRequestUri) {
AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(authenticationRequestUri);
return mockAuthenticationRequest;
}
Test Case ID #spring-security_Test_49_2
Test Case Name: removeAuthenticationRequestWhenAttributeInSessionThenRemoveAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\servlet\HttpSessionSaml2AuthenticationRequestRepositoryTests.java)
Mock Object Variable Name: mockAuthenticationRequest
Suggested Diff
@@
public void removeAuthenticationRequestWhenAttributeInSessionThenRemoveAuthenticationRequest() {
- AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
- given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL);
+ AbstractSaml2AuthenticationRequest mockAuthenticationRequest = createMockAuthenticationRequest(IDP_SSO_URL);
this.request.getSession();
this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository.removeAuthenticationRequest(this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequestAfterRemove = this.authenticationRequestRepository.loadAuthenticationRequest(this.request);
assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL);
assertThat(authenticationRequestAfterRemove).isNull();
}
Original Test Code (click to expand)
@Test
public void removeAuthenticationRequestWhenAttributeInSessionThenRemoveAuthenticationRequest() {
AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL);
this.request.getSession();
this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository.removeAuthenticationRequest(this.request, this.response);
AbstractSaml2AuthenticationRequest authenticationRequestAfterRemove = this.authenticationRequestRepository.loadAuthenticationRequest(this.request);
assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL);
assertThat(authenticationRequestAfterRemove).isNull();
}
Reusable Method for MCI (click to expand)
private static AbstractSaml2AuthenticationRequest createMockAuthenticationRequest(String authenticationRequestUri) {
AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(authenticationRequestUri);
return mockAuthenticationRequest;
}
Mock Clone Instance #spring-security_MCI_50
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.ott.reactive.ReactiveOneTimeTokenService
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ReactiveOneTimeTokenService createMockOneTimeTokenServiceReturning(Mono<?> consumeReturn) {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(consumeReturn);
return oneTimeTokenService;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_50_1
Test Case Name: authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ott\reactive\OneTimeTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: oneTimeTokenService
Suggested Diff
@@
void authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail() {
- ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
- given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
+ ReactiveOneTimeTokenService oneTimeTokenService = createMockOneTimeTokenServiceReturning(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
// @formatter:off
assertThatExceptionOfType(InvalidOneTimeTokenException.class).isThrownBy(() -> this.authenticationManager.authenticate(OneTimeTokenAuthenticationToken.unauthenticated(TOKEN)).block());
// @formatter:on
}
Original Test Code (click to expand)
@Test
void authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
assertThatExceptionOfType(InvalidOneTimeTokenException.class).isThrownBy(() -> this.authenticationManager.authenticate(OneTimeTokenAuthenticationToken.unauthenticated(TOKEN)).block());
}
Reusable Method for MCI (click to expand)
private static ReactiveOneTimeTokenService createMockOneTimeTokenServiceReturning(Mono<?> consumeReturn) {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(consumeReturn);
return oneTimeTokenService;
}
Test Case ID #spring-security_Test_50_2
Test Case Name: authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ott\reactive\OneTimeTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: oneTimeTokenService
Suggested Diff
@@
void authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail() {
- ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
- given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
+ ReactiveOneTimeTokenService oneTimeTokenService = createMockOneTimeTokenServiceReturning(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
// @formatter:off
Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD)).block();
// @formatter:on
assertThat(authentication).isNull();
}
Original Test Code (click to expand)
@Test
void authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD)).block();
assertThat(authentication).isNull();
}
Reusable Method for MCI (click to expand)
private static ReactiveOneTimeTokenService createMockOneTimeTokenServiceReturning(Mono<?> consumeReturn) {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(consumeReturn);
return oneTimeTokenService;
}
Mock Clone Instance #spring-security_MCI_51
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.ServerRedirectStrategy
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServerRedirectStrategy createMockServerRedirectStrategy() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
return authorizationRedirectStrategy;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_51_1
Mock Object Variable Name: authorizationRedirectStrategy
Suggested Diff
@@
@Test
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Login() {
- ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
+ ServerRedirectStrategy authorizationRedirectStrategy = createMockServerRedirectStrategy();
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
- given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
@@
Original Test Code (click to expand)
@Test
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Login() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
Reusable Method for MCI (click to expand)
private static ServerRedirectStrategy createMockServerRedirectStrategy() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
return authorizationRedirectStrategy;
}
Test Case ID #spring-security_Test_51_2
Mock Object Variable Name: authorizationRedirectStrategy
Suggested Diff
@@
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Client() {
- ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
+ ServerRedirectStrategy authorizationRedirectStrategy = createMockServerRedirectStrategy();
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
- given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
Original Test Code (click to expand)
@Test
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Client() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
Reusable Method for MCI (click to expand)
private static ServerRedirectStrategy createMockServerRedirectStrategy() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
return authorizationRedirectStrategy;
}
Mock Clone Instance #spring-security_MCI_52
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.ServerRedirectStrategy
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockServerRedirectStrategy {
public static ServerRedirectStrategy createMockServerRedirectStrategy(Mono<Void> sendRedirectReturn) {
ServerRedirectStrategy redirectStrategy = mock(ServerRedirectStrategy.class);
given(redirectStrategy.sendRedirect(any(), any())).willReturn(sendRedirectReturn);
return redirectStrategy;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_52_1
Test Case Name: commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\RedirectServerAuthenticationEntryPointTests.java)
Mock Object Variable Name: redirectStrategy
Suggested Diff
@@
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
- given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
- this.entryPoint.setRedirectStrategy(this.redirectStrategy);
+ this.redirectStrategy = MockServerRedirectStrategy.createMockServerRedirectStrategy(redirectResult.mono());
+ this.entryPoint.setRedirectStrategy(this.redirectStrategy);
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
this.entryPoint.commence(this.exchange, this.exception).block();
redirectResult.assertWasSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.entryPoint.setRedirectStrategy(this.redirectStrategy);
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
this.entryPoint.commence(this.exchange, this.exception).block();
redirectResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
public class MockServerRedirectStrategy {
public static ServerRedirectStrategy createMockServerRedirectStrategy(Mono<Void> sendRedirectReturn) {
ServerRedirectStrategy redirectStrategy = mock(ServerRedirectStrategy.class);
given(redirectStrategy.sendRedirect(any(), any())).willReturn(sendRedirectReturn);
return redirectStrategy;
}
}
Test Case ID #spring-security_Test_52_2
Test Case Name: commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\RedirectServerAuthenticationFailureHandlerTests.java)
Mock Object Variable Name: redirectStrategy
Suggested Diff
@@
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
- given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
- this.handler.setRedirectStrategy(this.redirectStrategy);
+ this.redirectStrategy = MockServerRedirectStrategy.createMockServerRedirectStrategy(redirectResult.mono());
+ this.handler.setRedirectStrategy(this.redirectStrategy);
this.exchange = createExchange();
this.handler.onAuthenticationFailure(this.exchange, this.exception).block();
redirectResult.assertWasSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void commenceWhenCustomServerRedirectStrategyThenCustomServerRedirectStrategyUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.handler.setRedirectStrategy(this.redirectStrategy);
this.exchange = createExchange();
this.handler.onAuthenticationFailure(this.exchange, this.exception).block();
redirectResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
public class MockServerRedirectStrategy {
public static ServerRedirectStrategy createMockServerRedirectStrategy(Mono<Void> sendRedirectReturn) {
ServerRedirectStrategy redirectStrategy = mock(ServerRedirectStrategy.class);
given(redirectStrategy.sendRedirect(any(), any())).willReturn(sendRedirectReturn);
return redirectStrategy;
}
}
Test Case ID #spring-security_Test_52_3
Test Case Name: successWhenCustomLocationThenCustomLocationUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\RedirectServerAuthenticationSuccessHandlerTests.java)
Mock Object Variable Name: redirectStrategy
Suggested Diff
@@
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
- given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
+ this.redirectStrategy = MockServerRedirectStrategy.createMockServerRedirectStrategy(redirectResult.mono());
this.handler.setRedirectStrategy(this.redirectStrategy);
Original Test Code (click to expand)
@Test
public void successWhenCustomLocationThenCustomLocationUsed() {
PublisherProbe<Void> redirectResult = PublisherProbe.empty();
given(this.redirectStrategy.sendRedirect(any(), any())).willReturn(redirectResult.mono());
this.handler.setRedirectStrategy(this.redirectStrategy);
this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
this.handler.onAuthenticationSuccess(new WebFilterExchange(this.exchange, this.chain), this.authentication).block();
redirectResult.assertWasSubscribed();
verify(this.redirectStrategy).sendRedirect(any(), eq(this.location));
}
Reusable Method for MCI (click to expand)
public class MockServerRedirectStrategy {
public static ServerRedirectStrategy createMockServerRedirectStrategy(Mono<Void> sendRedirectReturn) {
ServerRedirectStrategy redirectStrategy = mock(ServerRedirectStrategy.class);
given(redirectStrategy.sendRedirect(any(), any())).willReturn(sendRedirectReturn);
return redirectStrategy;
}
}
Mock Clone Instance #spring-security_MCI_53
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.context.ServerSecurityContextRepository
- Test Case Count: 2
- MO Count: 3
Reusable Method
public class MockServerSecurityContextRepository {
public static ServerSecurityContextRepository createMockServerSecurityContextRepository(Mono<SecurityContext> loadReturn) {
ServerSecurityContextRepository mockRepository = mock(ServerSecurityContextRepository.class);
given(mockRepository.load(any())).willReturn(loadReturn);
return mockRepository;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_53_1
Test Case Name: formLoginSecurityContextRepository(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\FormLoginTests.java)
Mock Object Variable Name: defaultSecContextRepository
Suggested Diff
@@
public void formLoginSecurityContextRepository() {
- ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class);
+ ServerSecurityContextRepository defaultSecContextRepository = MockServerSecurityContextRepository.createMockServerSecurityContextRepository(authentication(token));
ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class);
TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER");
- given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty());
- given(defaultSecContextRepository.load(any())).willReturn(authentication(token));
given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(formLoginSecContextRepository.load(any())).willReturn(authentication(token));
// @formatter:off
SecurityWebFilterChain securityWebFilter = this.http.authorizeExchange().anyExchange().authenticated().and().securityContextRepository(defaultSecContextRepository).formLogin().securityContextRepository(formLoginSecContextRepository).and().build();
@@
Original Test Code (click to expand)
@Test
public void formLoginSecurityContextRepository() {
ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class);
ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class);
TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER");
given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(defaultSecContextRepository.load(any())).willReturn(authentication(token));
given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(formLoginSecContextRepository.load(any())).willReturn(authentication(token));
SecurityWebFilterChain securityWebFilter = this.http.authorizeExchange().anyExchange().authenticated().and().securityContextRepository(defaultSecContextRepository).formLogin().securityContextRepository(formLoginSecContextRepository).and().build();
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();
DefaultLoginPage loginPage = DefaultLoginPage.to(driver).assertAt();
HomePage homePage = loginPage.loginForm().username("user").password("password").submit(HomePage.class);
homePage.assertAt();
verify(defaultSecContextRepository, atLeastOnce()).load(any());
verify(formLoginSecContextRepository).save(any(), any());
}
Reusable Method for MCI (click to expand)
public class MockServerSecurityContextRepository {
public static ServerSecurityContextRepository createMockServerSecurityContextRepository(Mono<SecurityContext> loadReturn) {
ServerSecurityContextRepository mockRepository = mock(ServerSecurityContextRepository.class);
given(mockRepository.load(any())).willReturn(loadReturn);
return mockRepository;
}
}
Test Case ID #spring-security_Test_53_2
Test Case Name: formLoginSecurityContextRepository(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\FormLoginTests.java)
Mock Object Variable Name: formLoginSecContextRepository
Suggested Diff
@@
ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class);
- ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class);
TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER");
given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(defaultSecContextRepository.load(any())).willReturn(authentication(token));
+ ServerSecurityContextRepository formLoginSecContextRepository = MockServerSecurityContextRepository.createMockServerSecurityContextRepository(authentication(token));
given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty());
// @formatter:off
SecurityWebFilterChain securityWebFilter = this.http.authorizeExchange().anyExchange().authenticated().and().securityContextRepository(defaultSecContextRepository).formLogin().securityContextRepository(formLoginSecContextRepository).and().build();
@@
Original Test Code (click to expand)
@Test
public void formLoginSecurityContextRepository() {
ServerSecurityContextRepository defaultSecContextRepository = mock(ServerSecurityContextRepository.class);
ServerSecurityContextRepository formLoginSecContextRepository = mock(ServerSecurityContextRepository.class);
TestingAuthenticationToken token = new TestingAuthenticationToken("rob", "rob", "ROLE_USER");
given(defaultSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(defaultSecContextRepository.load(any())).willReturn(authentication(token));
given(formLoginSecContextRepository.save(any(), any())).willReturn(Mono.empty());
given(formLoginSecContextRepository.load(any())).willReturn(authentication(token));
SecurityWebFilterChain securityWebFilter = this.http.authorizeExchange().anyExchange().authenticated().and().securityContextRepository(defaultSecContextRepository).formLogin().securityContextRepository(formLoginSecContextRepository).and().build();
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();
DefaultLoginPage loginPage = DefaultLoginPage.to(driver).assertAt();
HomePage homePage = loginPage.loginForm().username("user").password("password").submit(HomePage.class);
homePage.assertAt();
verify(defaultSecContextRepository, atLeastOnce()).load(any());
verify(formLoginSecContextRepository).save(any(), any());
}
Reusable Method for MCI (click to expand)
public class MockServerSecurityContextRepository {
public static ServerSecurityContextRepository createMockServerSecurityContextRepository(Mono<SecurityContext> loadReturn) {
ServerSecurityContextRepository mockRepository = mock(ServerSecurityContextRepository.class);
given(mockRepository.load(any())).willReturn(loadReturn);
return mockRepository;
}
}
Test Case ID #spring-security_Test_53_3
Test Case Name: defaults(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: contextRepository
Suggested Diff
@@
TestPublisher<SecurityContext> securityContext = TestPublisher.create();
- given(this.contextRepository.load(any())).willReturn(securityContext.mono());
+ this.contextRepository = MockServerSecurityContextRepository.createMockServerSecurityContextRepository(securityContext.mono());
this.http.securityContextRepository(this.contextRepository);
WebTestClient client = buildClient();
Original Test Code (click to expand)
@Test
public void defaults() {
TestPublisher<SecurityContext> securityContext = TestPublisher.create();
given(this.contextRepository.load(any())).willReturn(securityContext.mono());
this.http.securityContextRepository(this.contextRepository);
WebTestClient client = buildClient();
FluxExchangeResult<String> result = client.get().uri("/").exchange().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").returnResult(String.class);
assertThat(result.getResponseCookies()).isEmpty();
securityContext.assertWasNotSubscribed();
}
Reusable Method for MCI (click to expand)
public class MockServerSecurityContextRepository {
public static ServerSecurityContextRepository createMockServerSecurityContextRepository(Mono<SecurityContext> loadReturn) {
ServerSecurityContextRepository mockRepository = mock(ServerSecurityContextRepository.class);
given(mockRepository.load(any())).willReturn(loadReturn);
return mockRepository;
}
}
Mock Clone Instance #spring-security_MCI_54
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.AuthenticationManager
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthenticationManager createMockAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
return am;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_54_1
Test Case Name: filterChainProceedsOnFailedAuthenticationByDefault(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
@Test
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
+ AuthenticationManager am = createMockAuthenticationManager();
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
return am;
}
Test Case ID #spring-security_Test_54_2
Test Case Name: exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception {
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
+ AuthenticationManager am = createMockAuthenticationManager();
this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
return am;
}
Mock Clone Instance #spring-security_MCI_55
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.AuthenticationManager
- Test Case Count: 11
- MO Count: 11
Reusable Method
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
The refactoring details in each test cases
Test Case ID #spring-security_Test_55_1
Test Case Name: testAfterPropertiesSetInvokesSuper(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
@Test
public void testAfterPropertiesSetInvokesSuper() {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
assertThat(filter.initFilterBeanInvoked).isTrue();
}
Original Test Code (click to expand)
@Test
public void testAfterPropertiesSetInvokesSuper() {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
assertThat(filter.initFilterBeanInvoked).isTrue();
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_2
Test Case Name: requiresAuthenticationFalsePrincipalString(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
Original Test Code (click to expand)
@Test
public void requiresAuthenticationFalsePrincipalString() throws Exception {
Object principal = "sameprincipal";
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_3
Test Case Name: requiresAuthenticationTruePrincipalString(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = "newUser";
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
- verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
+ verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
Original Test Code (click to expand)
@Test
public void requiresAuthenticationTruePrincipalString() throws Exception {
Object currentPrincipal = "currentUser";
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = "newUser";
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_4
Test Case Name: callsAuthenticationSuccessHandlerOnSuccessfulAuthentication(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = "newUser";
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
- verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
+ verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
Original Test Code (click to expand)
@Test
public void callsAuthenticationSuccessHandlerOnSuccessfulAuthentication() throws Exception {
Object currentPrincipal = "currentUser";
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setAuthenticationSuccessHandler(new ForwardAuthenticationSuccessHandler("/forwardUrl"));
filter.setCheckForPrincipalChanges(true);
filter.principal = "newUser";
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_5
Test Case Name: requiresAuthenticationFalsePrincipalNotString(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
Original Test Code (click to expand)
@Test
public void requiresAuthenticationFalsePrincipalNotString() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_6
Test Case Name: requiresAuthenticationFalsePrincipalUser(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES);
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
Original Test Code (click to expand)
@Test
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken currentAuthentication = UsernamePasswordAuthenticationToken.authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES);
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_7
Test Case Name: requiresAuthenticationTruePrincipalNotString(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
filter.principal = new Object();
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
- verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
+ verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
Original Test Code (click to expand)
@Test
public void requiresAuthenticationTruePrincipalNotString() throws Exception {
Object currentPrincipal = new Object();
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = new Object();
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_8
Test Case Name: requiresAuthenticationOverridePrincipalChangedTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
- verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
+ verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
Original Test Code (click to expand)
@Test
public void requiresAuthenticationOverridePrincipalChangedTrue() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
return true;
}
};
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_9
Test Case Name: requiresAuthenticationOverridePrincipalChangedFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setCheckForPrincipalChanges(true);
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
Original Test Code (click to expand)
@Test
public void requiresAuthenticationOverridePrincipalChangedFalse() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
return false;
}
};
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_10
Test Case Name: requestNotMatchRequestMatcher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/no-matching"));
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
Original Test Code (click to expand)
@Test
public void requestNotMatchRequestMatcher() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/no-matching"));
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(am);
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Test Case ID #spring-security_Test_55_11
Test Case Name: requestMatchesRequestMatcher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\preauth\AbstractPreAuthenticatedProcessingFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
@Test
public void requestMatchesRequestMatcher() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**"));
- AuthenticationManager am = mock(AuthenticationManager.class);
+ // removed local mock; replaced with global field `am`
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
Original Test Code (click to expand)
@Test
public void requestMatchesRequestMatcher() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**"));
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
Reusable Method for MCI (click to expand)
private AuthenticationManager am;
@BeforeEach
public void setUp() {
am = mock(AuthenticationManager.class);
}
am
Mock Clone Instance #spring-security_MCI_56
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.AuthenticationManager
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static AuthenticationManager createMockAuthenticationManager(Authentication remembered) {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(remembered)).willReturn(remembered);
return am;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_56_1
Test Case Name: testOperationWhenNoAuthenticationInContextHolder(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
@Test
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(this.remembered)).willReturn(this.remembered);
+ AuthenticationManager am = createMockAuthenticationManager(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter setup with our remembered authentication object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@
Original Test Code (click to expand)
@Test
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager(Authentication remembered) {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(remembered)).willReturn(remembered);
return am;
}
Test Case ID #spring-security_Test_56_2
Test Case Name: authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(this.remembered)).willReturn(this.remembered);
+ AuthenticationManager am = createMockAuthenticationManager(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
// Should return after success handler is invoked, so chain should not proceed
verifyNoMoreInteractions(fc);
}
Original Test Code (click to expand)
@Test
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
verifyNoMoreInteractions(fc);
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager(Authentication remembered) {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(remembered)).willReturn(remembered);
return am;
}
Test Case ID #spring-security_Test_56_3
Test Case Name: securityContextRepositoryInvokedIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(this.remembered)).willReturn(this.remembered);
+ AuthenticationManager am = createMockAuthenticationManager(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSecurityContextRepository(securityContextRepository);
@@
Original Test Code (click to expand)
@Test
public void securityContextRepositoryInvokedIfSet() throws Exception {
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSecurityContextRepository(securityContextRepository);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(securityContextRepository).saveContext(any(), eq(request), eq(response));
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager(Authentication remembered) {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(remembered)).willReturn(remembered);
return am;
}
Test Case ID #spring-security_Test_56_4
Test Case Name: sessionAuthenticationStrategyInvokedIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: am
Suggested Diff
@@
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
- AuthenticationManager am = mock(AuthenticationManager.class);
- given(am.authenticate(this.remembered)).willReturn(this.remembered);
+ AuthenticationManager am = createMockAuthenticationManager(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(sessionAuthenticationStrategy).onAuthentication(any(), eq(request), eq(response));
@@
Original Test Code (click to expand)
@Test
public void sessionAuthenticationStrategyInvokedIfSet() throws Exception {
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(sessionAuthenticationStrategy).onAuthentication(any(), eq(request), eq(response));
}
Reusable Method for MCI (click to expand)
private static AuthenticationManager createMockAuthenticationManager(Authentication remembered) {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(remembered)).willReturn(remembered);
return am;
}
Mock Clone Instance #spring-security_MCI_57
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver
- Test Case Count: 6
- MO Count: 6
Reusable Method
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_57_1
Test Case Name: resolveWhenCustomParametersConsumerThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml4LogoutResponseResolverTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().assertingPartyDetails((party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")).build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(this.saml.serialize(logoutRequest).serialize().getBytes()));
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication);
assertThat(logoutResponse).isNotNull();
verify(parametersConsumer).accept(any());
@@
Original Test Code (click to expand)
@Test
public void resolveWhenCustomParametersConsumerThenUses() {
OpenSaml4LogoutResponseResolver logoutResponseResolver = new OpenSaml4LogoutResponseResolver(this.relyingPartyRegistrationResolver);
Consumer<LogoutResponseParameters> parametersConsumer = mock(Consumer.class);
logoutResponseResolver.setParametersConsumer(parametersConsumer);
MockHttpServletRequest request = new MockHttpServletRequest();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().assertingPartyDetails((party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")).build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(this.saml.serialize(logoutRequest).serialize().getBytes()));
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication);
assertThat(logoutResponse).isNotNull();
verify(parametersConsumer).accept(any());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Test Case ID #spring-security_Test_57_2
Test Case Name: resolveWhenCustomParametersConsumerThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutResponseResolverTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().assertingPartyDetails((party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")).build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(this.saml.serialize(logoutRequest).serialize().getBytes()));
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication);
assertThat(logoutResponse).isNotNull();
verify(parametersConsumer).accept(any());
Original Test Code (click to expand)
@Test
public void resolveWhenCustomParametersConsumerThenUses() {
OpenSaml5LogoutResponseResolver logoutResponseResolver = new OpenSaml5LogoutResponseResolver(this.relyingPartyRegistrationResolver);
Consumer<LogoutResponseParameters> parametersConsumer = mock(Consumer.class);
logoutResponseResolver.setParametersConsumer(parametersConsumer);
MockHttpServletRequest request = new MockHttpServletRequest();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().assertingPartyDetails((party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")).build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(this.saml.serialize(logoutRequest).serialize().getBytes()));
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication);
assertThat(logoutResponse).isNotNull();
verify(parametersConsumer).accept(any());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Test Case ID #spring-security_Test_57_3
Test Case Name: doFilterWhenSamlRequestThenRedirects(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\Saml2LogoutRequestFilterTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success());
Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse("response").build();
Original Test Code (click to expand)
@Test
public void doFilterWhenSamlRequestThenRedirects() throws Exception {
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
SecurityContextHolder.getContext().setAuthentication(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo");
request.setServletPath("/logout/saml2/slo");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
MockHttpServletResponse response = new MockHttpServletResponse();
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success());
Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse("response").build();
given(this.logoutResponseResolver.resolve(any(), any())).willReturn(logoutResponse);
this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
verify(this.logoutRequestValidator).validate(any());
verify(this.logoutHandler).logout(any(), any(), any());
verify(this.logoutResponseResolver).resolve(any(), any());
String content = response.getHeader("Location");
assertThat(content).contains(Saml2ParameterNames.SAML_RESPONSE);
assertThat(content).startsWith(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Test Case ID #spring-security_Test_57_4
Test Case Name: doFilterWhenSamlRequestThenPosts(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\Saml2LogoutRequestFilterTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo");
request.setServletPath("/logout/saml2/slo");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
MockHttpServletResponse response = new MockHttpServletResponse();
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success());
Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse("response").build();
given(this.logoutResponseResolver.resolve(any(), any())).willReturn(logoutResponse);
this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenSamlRequestThenPosts() throws Exception {
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build();
Authentication authentication = new TestingAuthenticationToken("user", "password");
given(this.securityContextHolderStrategy.getContext()).willReturn(new SecurityContextImpl(authentication));
this.logoutRequestProcessingFilter.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
SecurityContextHolder.getContext().setAuthentication(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo");
request.setServletPath("/logout/saml2/slo");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
MockHttpServletResponse response = new MockHttpServletResponse();
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success());
Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse("response").build();
given(this.logoutResponseResolver.resolve(any(), any())).willReturn(logoutResponse);
this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
verify(this.logoutRequestValidator).validate(any());
verify(this.logoutHandler).logout(any(), any(), any());
verify(this.logoutResponseResolver).resolve(any(), any());
String content = response.getContentAsString();
assertThat(content).contains(Saml2ParameterNames.SAML_RESPONSE);
assertThat(content).contains(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation());
assertThat(content).contains("<meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">");
assertThat(content).contains("<script>window.onload = function() { document.forms[0].submit(); }</script>");
verify(this.securityContextHolderStrategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Test Case ID #spring-security_Test_57_5
Test Case Name: doFilterWhenNoRelyingPartyLogoutThen401(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\Saml2LogoutRequestFilterTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null).build();
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
assertThat(response.getStatus()).isEqualTo(401);
verifyNoInteractions(this.logoutHandler);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception {
Authentication authentication = new TestingAuthenticationToken("user", "password");
SecurityContextHolder.getContext().setAuthentication(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo");
request.setServletPath("/logout/saml2/slo");
request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request");
MockHttpServletResponse response = new MockHttpServletResponse();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null).build();
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
assertThat(response.getStatus()).isEqualTo(401);
verifyNoInteractions(this.logoutHandler);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Test Case ID #spring-security_Test_57_6
Test Case Name: doFilterWhenNoRelyingPartyLogoutThen401(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\logout\Saml2LogoutResponseFilterTests.java)
Mock Object Variable Name: relyingPartyRegistrationResolver
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null).singleLogoutServiceResponseLocation(null).build();
- given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
+ this.relyingPartyRegistrationResolver = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).samlRequest("request").build();
given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest);
this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
assertThat(response.getStatus()).isEqualTo(401);
verifyNoInteractions(this.logoutSuccessHandler);
Original Test Code (click to expand)
@Test
public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception {
Authentication authentication = new TestingAuthenticationToken("user", "password");
SecurityContextHolder.getContext().setAuthentication(authentication);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo");
request.setServletPath("/logout/saml2/slo");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response");
MockHttpServletResponse response = new MockHttpServletResponse();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null).singleLogoutServiceResponseLocation(null).build();
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).samlRequest("request").build();
given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest);
this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain());
assertThat(response.getStatus()).isEqualTo(401);
verifyNoInteractions(this.logoutSuccessHandler);
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class);
given(relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration);
return relyingPartyRegistrationResolver;
}
}
Mock Clone Instance #spring-security_MCI_58
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver
- Test Case Count: 4
- MO Count: 8
Reusable Method
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_58_1
Test Case Name: resolveWhenRedirectThenSaml2RedirectAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml4AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenRedirectThenSaml2RedirectAuthenticationRequest() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Original Test Code (click to expand)
@Test
void resolveWhenRedirectThenSaml2RedirectAuthenticationRequest() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_2
Test Case Name: resolveWhenPostThenSaml2PostAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml4AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
Saml2PostAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
@@
Original Test Code (click to expand)
@Test
void resolveWhenPostThenSaml2PostAuthenticationRequest() {
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
Saml2PostAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_3
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml4AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenCustomRelayStateThenUses() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Original Test Code (click to expand)
@Test
void resolveWhenCustomRelayStateThenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_4
Test Case Name: resolveWhenCustomAuthenticationUrlTHenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml4AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenCustomAuthenticationUrlTHenUses() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRequestMatcher(new AntPathRequestMatcher("/custom/authentication/{registrationId}"));
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(givenRequest("/custom/authentication/registration-id"));
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Original Test Code (click to expand)
@Test
void resolveWhenCustomAuthenticationUrlTHenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties);
resolver.setRequestMatcher(new AntPathRequestMatcher("/custom/authentication/{registrationId}"));
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(givenRequest("/custom/authentication/registration-id"));
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_5
Test Case Name: resolveWhenRedirectThenSaml2RedirectAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenRedirectThenSaml2RedirectAuthenticationRequest() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Original Test Code (click to expand)
@Test
void resolveWhenRedirectThenSaml2RedirectAuthenticationRequest() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_6
Test Case Name: resolveWhenPostThenSaml2PostAuthenticationRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
Saml2PostAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
@@
Original Test Code (click to expand)
@Test
void resolveWhenPostThenSaml2PostAuthenticationRequest() {
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
Saml2PostAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_7
Test Case Name: resolveWhenCustomRelayStateThenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenCustomRelayStateThenUses() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Original Test Code (click to expand)
@Test
void resolveWhenCustomRelayStateThenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
Converter<HttpServletRequest, String> relayState = mock(Converter.class);
given(relayState.convert(any())).willReturn("state");
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRelayStateResolver(relayState);
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request);
assertThat(authnRequest.getRelayState()).isEqualTo("state");
verify(relayState).convert(any());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Test Case ID #spring-security_Test_58_8
Test Case Name: resolveWhenCustomAuthenticationUrlTHenUses(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolverTests.java)
Mock Object Variable Name: relyingParties
Suggested Diff
@@
void resolveWhenCustomAuthenticationUrlTHenUses() {
- RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
- given(relyingParties.resolve(any(), any())).willReturn(this.registration);
+ RelyingPartyRegistrationResolver relyingParties = MockRelyingPartyRegistrationResolver.createMockRelyingPartyRegistrationResolver(this.registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRequestMatcher(new AntPathRequestMatcher("/custom/authentication/{registrationId}"));
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(givenRequest("/custom/authentication/registration-id"));
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
@@
Original Test Code (click to expand)
@Test
void resolveWhenCustomAuthenticationUrlTHenUses() {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(this.registration);
OpenSaml5AuthenticationRequestResolver resolver = new OpenSaml5AuthenticationRequestResolver(relyingParties);
resolver.setRequestMatcher(new AntPathRequestMatcher("/custom/authentication/{registrationId}"));
Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(givenRequest("/custom/authentication/registration-id"));
assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT);
assertThat(authnRequest.getAuthenticationRequestUri()).isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation());
}
Reusable Method for MCI (click to expand)
public class MockRelyingPartyRegistrationResolver {
public static RelyingPartyRegistrationResolver createMockRelyingPartyRegistrationResolver(RelyingPartyRegistration registration) {
RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class);
given(relyingParties.resolve(any(), any())).willReturn(registration);
return relyingParties;
}
}
Mock Clone Instance #spring-security_MCI_59
- Scope: method level
- Mocked Class:
org.apereo.cas.client.validation.TicketValidator
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static TicketValidator createMockTicketValidator(AssertionImpl assertion) {
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(assertion);
return validator;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_59_1
Test Case Name: authenticateAllNullService(File: C:\Java_projects\Spring\spring-security\cas\src\test\java\org\springframework\security\cas\authentication\CasAuthenticationProviderTests.java)
Mock Object Variable Name: validator
Suggested Diff
@@
given(details.getServiceUrl()).willReturn(serviceUrl);
- TicketValidator validator = mock(TicketValidator.class);
- given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
+ TicketValidator validator = createMockTicketValidator(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
@@
Original Test Code (click to expand)
@Test
public void authenticateAllNullService() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket);
Authentication result = cap.authenticate(token);
}
Reusable Method for MCI (click to expand)
private static TicketValidator createMockTicketValidator(AssertionImpl assertion) {
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(assertion);
return validator;
}
Test Case ID #spring-security_Test_59_2
Test Case Name: authenticateAllAuthenticationIsSuccessful(File: C:\Java_projects\Spring\spring-security\cas\src\test\java\org\springframework\security\cas\authentication\CasAuthenticationProviderTests.java)
Mock Object Variable Name: validator
Suggested Diff
@@
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
- TicketValidator validator = mock(TicketValidator.class);
- given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
+ TicketValidator validator = createMockTicketValidator(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket);
Authentication result = cap.authenticate(token);
verify(validator).validate(ticket, serviceProperties.getService());
serviceProperties.setAuthenticateAllArtifacts(true);
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceProperties.getService());
token.setDetails(details);
result = cap.authenticate(token);
verify(validator).validate(ticket, serviceUrl);
serviceProperties.setAuthenticateAllArtifacts(false);
serviceProperties.setService(null);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.setServiceProperties(null);
cap.afterPropertiesSet();
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
@@
Original Test Code (click to expand)
@Test
public void authenticateAllAuthenticationIsSuccessful() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket);
Authentication result = cap.authenticate(token);
verify(validator).validate(ticket, serviceProperties.getService());
serviceProperties.setAuthenticateAllArtifacts(true);
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceProperties.getService());
token.setDetails(details);
result = cap.authenticate(token);
verify(validator).validate(ticket, serviceUrl);
serviceProperties.setAuthenticateAllArtifacts(false);
serviceProperties.setService(null);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.setServiceProperties(null);
cap.afterPropertiesSet();
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
}
Reusable Method for MCI (click to expand)
private static TicketValidator createMockTicketValidator(AssertionImpl assertion) {
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(assertion);
return validator;
}
Mock Clone Instance #spring-security_MCI_60
- Scope: class level
- Mocked Class:
javax.naming.directory.DirContext
- Test Case Count: 4
- MO Count: 4
Reusable Method
public class MockDirContext {
public static DirContext createMockDirContext(String nameInNamespace) {
DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn(nameInNamespace);
return mockCtx;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_60_1
Test Case Name: testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\LdapUtilsTests.java)
Mock Object Variable Name: mockCtx
Suggested Diff
@@
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
- final DirContext mockCtx = mock(DirContext.class);
- given(mockCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
+ final DirContext mockCtx = MockDirContext.createMockDirContext("dc=springframework,dc=org");
assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo("");
}
Original Test Code (click to expand)
@Test
public void testGetRelativeNameReturnsEmptyStringForDnEqualToBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
assertThat(LdapUtils.getRelativeName("dc=springframework,dc=org", mockCtx)).isEqualTo("");
}
Reusable Method for MCI (click to expand)
public class MockDirContext {
public static DirContext createMockDirContext(String nameInNamespace) {
DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn(nameInNamespace);
return mockCtx;
}
}
Test Case ID #spring-security_Test_60_2
Test Case Name: testGetRelativeNameReturnsFullDnWithEmptyBaseName(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\LdapUtilsTests.java)
Mock Object Variable Name: mockCtx
Suggested Diff
@@
@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
- final DirContext mockCtx = mock(DirContext.class);
- given(mockCtx.getNameInNamespace()).willReturn("");
+ final DirContext mockCtx = MockDirContext.createMockDirContext("");
assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)).isEqualTo("cn=jane,dc=springframework,dc=org");
}
@@
Original Test Code (click to expand)
@Test
public void testGetRelativeNameReturnsFullDnWithEmptyBaseName() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn("");
assertThat(LdapUtils.getRelativeName("cn=jane,dc=springframework,dc=org", mockCtx)).isEqualTo("cn=jane,dc=springframework,dc=org");
}
Reusable Method for MCI (click to expand)
public class MockDirContext {
public static DirContext createMockDirContext(String nameInNamespace) {
DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn(nameInNamespace);
return mockCtx;
}
}
Test Case ID #spring-security_Test_60_3
Test Case Name: testGetRelativeNameWorksWithArbitrarySpaces(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\LdapUtilsTests.java)
Mock Object Variable Name: mockCtx
Suggested Diff
@@
@Test
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
- final DirContext mockCtx = mock(DirContext.class);
- given(mockCtx.getNameInNamespace()).willReturn("dc=springsecurity,dc = org");
+ final DirContext mockCtx = MockDirContext.createMockDirContext("dc=springsecurity,dc = org");
assertThat(LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx)).isEqualTo("cn=jane smith");
}
@@
Original Test Code (click to expand)
@Test
public void testGetRelativeNameWorksWithArbitrarySpaces() throws Exception {
final DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn("dc=springsecurity,dc = org");
assertThat(LdapUtils.getRelativeName("cn=jane smith, dc = springsecurity , dc=org", mockCtx)).isEqualTo("cn=jane smith");
}
Reusable Method for MCI (click to expand)
public class MockDirContext {
public static DirContext createMockDirContext(String nameInNamespace) {
DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn(nameInNamespace);
return mockCtx;
}
}
Test Case ID #spring-security_Test_60_4
Test Case Name: searchForSingleEntryInternalAllowsReferrals(File: C:\Java_projects\Spring\spring-security\ldap\src\test\java\org\springframework\security\ldap\SpringSecurityLdapTemplateTests.java)
Mock Object Variable Name: ctx
Suggested Diff
@@
DirContextAdapter searchResultObject = mock(DirContextAdapter.class);
- given(this.ctx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
+ this.ctx = MockDirContext.createMockDirContext("dc=springframework,dc=org");
given(this.ctx.search(any(Name.class), eq(filter), eq(params), this.searchControls.capture())).willReturn(this.resultsEnum);
given(this.resultsEnum.hasMore()).willReturn(true, false);
Original Test Code (click to expand)
@Test
public void searchForSingleEntryInternalAllowsReferrals() throws Exception {
String base = "";
String filter = "";
String searchResultName = "ldap://example.com/dc=springframework,dc=org";
Object[] params = new Object[] {};
DirContextAdapter searchResultObject = mock(DirContextAdapter.class);
given(this.ctx.getNameInNamespace()).willReturn("dc=springframework,dc=org");
given(this.ctx.search(any(Name.class), eq(filter), eq(params), this.searchControls.capture())).willReturn(this.resultsEnum);
given(this.resultsEnum.hasMore()).willReturn(true, false);
given(this.resultsEnum.next()).willReturn(this.searchResult);
given(this.searchResult.getObject()).willReturn(searchResultObject);
SpringSecurityLdapTemplate.searchForSingleEntryInternal(this.ctx, mock(SearchControls.class), base, filter, params);
assertThat(this.searchControls.getValue().getReturningObjFlag()).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockDirContext {
public static DirContext createMockDirContext(String nameInNamespace) {
DirContext mockCtx = mock(DirContext.class);
given(mockCtx.getNameInNamespace()).willReturn(nameInNamespace);
return mockCtx;
}
}
Mock Clone Instance #spring-security_MCI_61
- Scope: method level
- Mocked Class:
org.springframework.security.web.AuthenticationEntryPoint
- Test Case Count: 3
- MO Count: 3
Reusable Method
private AuthenticationEntryPoint firstAEP;
@BeforeEach
public void setUp() {
firstAEP = mock(AuthenticationEntryPoint.class);
}
firstAEP
The refactoring details in each test cases
Test Case ID #spring-security_Test_61_1
Test Case Name: testDefaultEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstAEP
Suggested Diff
@@
@Test
public void testDefaultEntryPoint() throws Exception {
- AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
+ // removed local mock; replaced with global field `firstAEP`
RequestMatcher firstRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
- verify(firstAEP, never()).commence(this.request, null, null);
+ verify(firstAEP, never()).commence(this.request, null, null);
}
Original Test Code (click to expand)
@Test
public void testDefaultEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private AuthenticationEntryPoint firstAEP;
@BeforeEach
public void setUp() {
firstAEP = mock(AuthenticationEntryPoint.class);
}
firstAEP
Test Case ID #spring-security_Test_61_2
Test Case Name: testFirstEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstAEP
Suggested Diff
@@
@Test
public void testFirstEntryPoint() throws Exception {
- AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
+ // removed local mock; replaced with global field `firstAEP`
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(true);
- this.entryPoints.put(firstRM, firstAEP);
+ this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
- verify(firstAEP).commence(this.request, null, null);
+ verify(firstAEP).commence(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
verify(secondRM, never()).matches(this.request);
}
Original Test Code (click to expand)
@Test
public void testFirstEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(firstAEP).commence(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
verify(secondRM, never()).matches(this.request);
}
Reusable Method for MCI (click to expand)
private AuthenticationEntryPoint firstAEP;
@BeforeEach
public void setUp() {
firstAEP = mock(AuthenticationEntryPoint.class);
}
firstAEP
Test Case ID #spring-security_Test_61_3
Test Case Name: testSecondEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstAEP
Suggested Diff
@@
@Test
public void testSecondEntryPoint() throws Exception {
- AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
+ // removed local mock; replaced with global field `firstAEP`
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
- verify(firstAEP, never()).commence(this.request, null, null);
+ verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
}
Original Test Code (click to expand)
@Test
public void testSecondEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private AuthenticationEntryPoint firstAEP;
@BeforeEach
public void setUp() {
firstAEP = mock(AuthenticationEntryPoint.class);
}
firstAEP
Mock Clone Instance #spring-security_MCI_62
- Scope: method level
- Mocked Class:
org.springframework.security.web.access.AccessDeniedHandler
- Test Case Count: 3
- MO Count: 3
Reusable Method
private AccessDeniedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(AccessDeniedHandler.class);
}
handler
The refactoring details in each test cases
Test Case ID #spring-security_Test_62_1
Test Case Name: handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception {
- AccessDeniedHandler handler = mock(AccessDeniedHandler.class);
+ // removed local mock; replaced with global field `handler`
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(this.request)).willReturn(false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(this.accessDeniedHandler).handle(this.request, null, null);
- verify(handler, never()).handle(this.request, null, null);
+ verify(handler, never()).handle(this.request, null, null);
}
Original Test Code (click to expand)
@Test
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception {
AccessDeniedHandler handler = mock(AccessDeniedHandler.class);
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(this.request)).willReturn(false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(this.accessDeniedHandler).handle(this.request, null, null);
verify(handler, never()).handle(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private AccessDeniedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(AccessDeniedHandler.class);
}
handler
Test Case ID #spring-security_Test_62_2
Test Case Name: handleWhenFirstMatchesThenOnlyFirstInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstHandler
Suggested Diff
@@
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() throws Exception {
- AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
+ // removed local mock; replaced with global field `handler`
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(true);
- this.deniedHandlers.put(firstMatcher, firstHandler);
+ this.deniedHandlers.put(firstMatcher, handler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
- verify(firstHandler).handle(this.request, null, null);
+ verify(handler).handle(this.request, null, null);
verify(secondHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
verify(secondMatcher, never()).matches(this.request);
}
Original Test Code (click to expand)
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() throws Exception {
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(firstHandler).handle(this.request, null, null);
verify(secondHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
verify(secondMatcher, never()).matches(this.request);
}
Reusable Method for MCI (click to expand)
private AccessDeniedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(AccessDeniedHandler.class);
}
handler
Test Case ID #spring-security_Test_62_3
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstHandler
Suggested Diff
@@
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() throws Exception {
- AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
+ // removed local mock; replaced with global field `handler`
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(false);
given(secondMatcher.matches(this.request)).willReturn(true);
- this.deniedHandlers.put(firstMatcher, firstHandler);
+ this.deniedHandlers.put(firstMatcher, handler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
- verify(firstHandler, never()).handle(this.request, null, null);
+ verify(handler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
}
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() throws Exception {
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(false);
given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private AccessDeniedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(AccessDeniedHandler.class);
}
handler
Mock Clone Instance #spring-security_MCI_63
- Scope: method level
- Mocked Class:
org.springframework.web.client.RestOperations
- Test Case Count: 6
- MO Count: 6
Reusable Method
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_63_1
Test Case Name: decodeWhenIssuerLocationThenOk(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
String issuer = "https://example.org/issuer";
- RestOperations restOperations = mock(RestOperations.class);
- given(restOperations.exchange(any(RequestEntity.class), any(ParameterizedTypeReference.class))).willReturn(new ResponseEntity<>(Map.of("issuer", issuer, "jwks_uri", issuer + "/jwks"), HttpStatus.OK));
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ given(restOperations.exchange(any(RequestEntity.class), any(ParameterizedTypeReference.class))).willReturn(new ResponseEntity<>(Map.of("issuer", issuer, "jwks_uri", issuer + "/jwks"), HttpStatus.OK));
JwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(restOperations).build();
Jwt jwt = jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.hasClaim(JwtClaimNames.EXP)).isNotNull();
@@
Original Test Code (click to expand)
@Test
public void decodeWhenIssuerLocationThenOk() {
String issuer = "https://example.org/issuer";
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), any(ParameterizedTypeReference.class))).willReturn(new ResponseEntity<>(Map.of("issuer", issuer, "jwks_uri", issuer + "/jwks"), HttpStatus.OK));
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
JwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(restOperations).build();
Jwt jwt = jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.hasClaim(JwtClaimNames.EXP)).isNotNull();
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Test Case ID #spring-security_Test_63_2
Test Case Name: decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() {
- RestOperations restOperations = mock(RestOperations.class);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
JWTProcessor<SecurityContext> processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor();
// @formatter:on
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor);
jwtDecoder.decode(SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
@@
Original Test Code (click to expand)
@Test
public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
JWTProcessor<SecurityContext> processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor();
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor);
jwtDecoder.decode(SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Test Case ID #spring-security_Test_63_3
Test Case Name: decodeWhenCacheThenStoreRetrievedJwkSetToCache(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
- RestOperations restOperations = mock(RestOperations.class);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build();
// @formatter:on
jwtDecoder.decode(SIGNED_JWT);
assertThat(cache.get(JWK_SET_URI, String.class)).isEqualTo(JWK_SET);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
@@
Original Test Code (click to expand)
@Test
public void decodeWhenCacheThenStoreRetrievedJwkSetToCache() {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build();
jwtDecoder.decode(SIGNED_JWT);
assertThat(cache.get(JWK_SET_URI, String.class)).isEqualTo(JWK_SET);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Test Case ID #spring-security_Test_63_4
Test Case Name: decodeWhenCacheStoredThenAbleToRetrieveJwkSetFromCache(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
- RestOperations restOperations = mock(RestOperations.class);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder1 = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build();
@@
Original Test Code (click to expand)
@Test
public void decodeWhenCacheStoredThenAbleToRetrieveJwkSetFromCache() {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
NimbusJwtDecoder jwtDecoder1 = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build();
jwtDecoder1.decode(SIGNED_JWT);
assertThat(cache.get(JWK_SET_URI, String.class)).isEqualTo(JWK_SET);
verify(restOperations).exchange(any(RequestEntity.class), eq(String.class));
NimbusJwtDecoder jwtDecoder2 = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build();
jwtDecoder2.decode(SIGNED_JWT);
verifyNoMoreInteractions(restOperations);
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Test Case ID #spring-security_Test_63_5
Test Case Name: decodeWhenCacheAndUnknownKidShouldTriggerFetchOfJwkSet(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void decodeWhenCacheAndUnknownKidShouldTriggerFetchOfJwkSet() throws JOSEException {
- RestOperations restOperations = mock(RestOperations.class);
Cache cache = new ConcurrentMapCache("cache");
cache.put(JWK_SET_URI, JWK_SET);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(NEW_KID_JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(NEW_KID_JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).cache(cache).restOperations(restOperations).build();
// @formatter:on
// Decode JWT with new KID
jwtDecoder.decode(NEW_KID_SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
assertThat(requestEntityCaptor.getValue().getHeaders().getAccept()).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Original Test Code (click to expand)
@Test
public void decodeWhenCacheAndUnknownKidShouldTriggerFetchOfJwkSet() throws JOSEException {
RestOperations restOperations = mock(RestOperations.class);
Cache cache = new ConcurrentMapCache("cache");
cache.put(JWK_SET_URI, JWK_SET);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(NEW_KID_JWK_SET, HttpStatus.OK));
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).cache(cache).restOperations(restOperations).build();
jwtDecoder.decode(NEW_KID_SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
assertThat(requestEntityCaptor.getValue().getHeaders().getAccept()).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Test Case ID #spring-security_Test_63_6
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
- RestOperations restOperations = mock(RestOperations.class);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
+ RestOperations restOperations = createMockRestOperations(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("An error occurred while attempting to decode the Jwt: " + "Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).jwtProcessorCustomizer((p) -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))).build();
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("An error occurred while attempting to decode the Jwt: " + "Required JOSE header typ (type) parameter is missing");
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<?> exchangeReturnValue) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturnValue);
return restOperations;
}
Mock Clone Instance #spring-security_MCI_64
- Scope: method level
- Mocked Class:
org.springframework.web.client.RestOperations
- Test Case Count: 8
- MO Count: 8
Reusable Method
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_64_1
Test Case Name: introspectWhenInactiveTokenThenInvalidToken(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\introspection\NimbusOpaqueTokenIntrospectorTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
@Test
public void introspectWhenInactiveTokenThenInvalidToken() {
- RestOperations restOperations = mock(RestOperations.class);
+ RestOperations restOperations = createMockRestOperations(INACTIVE);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE);
// @formatter:off
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token")).withMessage("Provided token isn't active");
// @formatter:on
}
@@
Original Test Code (click to expand)
@Test
public void introspectWhenInactiveTokenThenInvalidToken() {
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token")).withMessage("Provided token isn't active");
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_2
Test Case Name: introspectWhenActiveTokenThenParsesValuesInResponse(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\introspection\NimbusOpaqueTokenIntrospectorTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L);
- RestOperations restOperations = mock(RestOperations.class);
+ RestOperations restOperations = createMockRestOperations(response(new JSONObject(introspectedValues).toJSONString()));
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response(new JSONObject(introspectedValues).toJSONString()));
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token");
// @formatter:off
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void introspectWhenActiveTokenThenParsesValuesInResponse() {
Map<String, Object> introspectedValues = new HashMap<>();
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true);
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"));
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L);
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response(new JSONObject(introspectedValues).toJSONString()));
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token");
assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID).doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_3
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void introspectWhenIntrospectionEndpointReturnsMalformedResponseThenInvalidToken() {
- RestOperations restOperations = mock(RestOperations.class);
+ RestOperations restOperations = createMockRestOperations(response("malformed"));
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed"));
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
Original Test Code (click to expand)
@Test
public void introspectWhenIntrospectionEndpointReturnsMalformedResponseThenInvalidToken() {
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed"));
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_4
Test Case Name: introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\introspection\NimbusOpaqueTokenIntrospectorTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() {
- RestOperations restOperations = mock(RestOperations.class);
+ RestOperations restOperations = createMockRestOperations(INVALID);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
@@
Original Test Code (click to expand)
@Test
public void introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() {
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_5
Mock Object Variable Name: restOperations
Suggested Diff
@@
@Test
public void introspectWhenIntrospectionTokenReturnsMalformedIssuerResponseThenInvalidToken() {
- RestOperations restOperations = mock(RestOperations.class);
- OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER);
+ RestOperations restOperations = createMockRestOperations(MALFORMED_ISSUER);
+ OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
@@
Original Test Code (click to expand)
@Test
public void introspectWhenIntrospectionTokenReturnsMalformedIssuerResponseThenInvalidToken() {
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("token"));
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_6
Mock Object Variable Name: restOperations
Suggested Diff
@@
// gh-7563
@Test
public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities() {
- RestOperations restOperations = mock(RestOperations.class);
+ RestOperations restOperations = createMockRestOperations(MALFORMED_SCOPE);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE);
OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token");
assertThat(principal.getAuthorities()).isEmpty();
JSONArray scope = principal.getAttribute("scope");
assertThat(scope).containsExactly("read", "write", "dolphin");
}
@@
Original Test Code (click to expand)
@Test
public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities() {
RestOperations restOperations = mock(RestOperations.class);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE);
OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token");
assertThat(principal.getAuthorities()).isEmpty();
JSONArray scope = principal.getAttribute("scope");
assertThat(scope).containsExactly("read", "write", "dolphin");
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_7
Test Case Name: handleMissingContentType(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\introspection\NimbusOpaqueTokenIntrospectorTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
@Test
public void handleMissingContentType() {
- RestOperations restOperations = mock(RestOperations.class);
ResponseEntity<String> stubResponse = ResponseEntity.ok(ACTIVE_RESPONSE);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse);
+ RestOperations restOperations = createMockRestOperations(stubResponse);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
// Protect against potential regressions where a default content type might be
// added by default.
assumeThat(stubResponse.getHeaders().getContentType()).isNull();
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("sometokenhere"));
}
@@
Original Test Code (click to expand)
@Test
public void handleMissingContentType() {
RestOperations restOperations = mock(RestOperations.class);
ResponseEntity<String> stubResponse = ResponseEntity.ok(ACTIVE_RESPONSE);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
assumeThat(stubResponse.getHeaders().getContentType()).isNull();
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("sometokenhere"));
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Test Case ID #spring-security_Test_64_8
Test Case Name: handleNonJsonContentType(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\introspection\NimbusOpaqueTokenIntrospectorTests.java)
Mock Object Variable Name: restOperations
Suggested Diff
@@
public void handleNonJsonContentType(String type) {
- RestOperations restOperations = mock(RestOperations.class);
ResponseEntity<String> stubResponse = ResponseEntity.ok().contentType(MediaType.parseMediaType(type)).body(ACTIVE_RESPONSE);
- given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse);
+ RestOperations restOperations = createMockRestOperations(stubResponse);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("sometokenhere"));
}
Original Test Code (click to expand)
@ParameterizedTest(name = "{displayName} when Content-Type={0}")
@ValueSource(strings = { MediaType.APPLICATION_CBOR_VALUE, MediaType.TEXT_MARKDOWN_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE })
public void handleNonJsonContentType(String type) {
RestOperations restOperations = mock(RestOperations.class);
ResponseEntity<String> stubResponse = ResponseEntity.ok().contentType(MediaType.parseMediaType(type)).body(ACTIVE_RESPONSE);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse);
OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations);
assertThatExceptionOfType(OAuth2IntrospectionException.class).isThrownBy(() -> introspectionClient.introspect("sometokenhere"));
}
Reusable Method for MCI (click to expand)
private static RestOperations createMockRestOperations(ResponseEntity<String> exchangeReturn) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(exchangeReturn);
return restOperations;
}
Mock Clone Instance #spring-security_MCI_65
- Scope: method level
- Mocked Class:
org.springframework.security.access.PermissionEvaluator
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static PermissionEvaluator createMockPermissionEvaluator(Authentication user, Object domainObject, String permission, boolean hasPermissionReturn) {
PermissionEvaluator pe = mock(PermissionEvaluator.class);
given(pe.hasPermission(user, domainObject, permission)).willReturn(hasPermissionReturn);
return pe;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_65_1
Test Case Name: hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\expression\method\MethodSecurityExpressionRootTests.java)
Mock Object Variable Name: pe
Suggested Diff
@@
final Object dummyDomainObject = new Object();
- final PermissionEvaluator pe = mock(PermissionEvaluator.class);
+ final PermissionEvaluator pe = createMockPermissionEvaluator(this.user, dummyDomainObject, "ignored", false);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
- given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(false);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
@@
Original Test Code (click to expand)
@Test
public void hasPermissionOnDomainObjectReturnsFalseIfPermissionEvaluatorDoes() {
final Object dummyDomainObject = new Object();
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(false);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isFalse();
}
Reusable Method for MCI (click to expand)
private static PermissionEvaluator createMockPermissionEvaluator(Authentication user, Object domainObject, String permission, boolean hasPermissionReturn) {
PermissionEvaluator pe = mock(PermissionEvaluator.class);
given(pe.hasPermission(user, domainObject, permission)).willReturn(hasPermissionReturn);
return pe;
}
Test Case ID #spring-security_Test_65_2
Test Case Name: hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\expression\method\MethodSecurityExpressionRootTests.java)
Mock Object Variable Name: pe
Suggested Diff
@@
final Object dummyDomainObject = new Object();
- final PermissionEvaluator pe = mock(PermissionEvaluator.class);
+ final PermissionEvaluator pe = createMockPermissionEvaluator(this.user, dummyDomainObject, "ignored", true);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
- given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(true);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
Original Test Code (click to expand)
@Test
public void hasPermissionOnDomainObjectReturnsTrueIfPermissionEvaluatorDoes() {
final Object dummyDomainObject = new Object();
final PermissionEvaluator pe = mock(PermissionEvaluator.class);
this.ctx.setVariable("domainObject", dummyDomainObject);
this.root.setPermissionEvaluator(pe);
given(pe.hasPermission(this.user, dummyDomainObject, "ignored")).willReturn(true);
assertThat(this.root.hasPermission(dummyDomainObject, "ignored")).isTrue();
}
Reusable Method for MCI (click to expand)
private static PermissionEvaluator createMockPermissionEvaluator(Authentication user, Object domainObject, String permission, boolean hasPermissionReturn) {
PermissionEvaluator pe = mock(PermissionEvaluator.class);
given(pe.hasPermission(user, domainObject, permission)).willReturn(hasPermissionReturn);
return pe;
}
Mock Clone Instance #spring-security_MCI_66
- Scope: method level
- Mocked Class:
org.springframework.security.web.firewall.HttpFirewall
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static HttpFirewall createMockHttpFirewall(MockHttpServletRequest request, FirewalledRequest fwr) {
HttpFirewall fw = mock(HttpFirewall.class);
given(fw.getFirewalledRequest(request)).willReturn(fwr);
return fw;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_66_1
Test Case Name: wrapperIsResetWhenNoMatchingFilters(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: fw
Suggested Diff
@@
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
- HttpFirewall fw = mock(HttpFirewall.class);
+ HttpFirewall fw = createMockHttpFirewall(this.request, fwr);
this.fcp.setFirewall(fw);
- given(fw.getFirewalledRequest(this.request)).willReturn(fwr);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
@@
Original Test Code (click to expand)
@Test
public void wrapperIsResetWhenNoMatchingFilters() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
this.fcp.setFirewall(fw);
given(fw.getFirewalledRequest(this.request)).willReturn(fwr);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
}
Reusable Method for MCI (click to expand)
private static HttpFirewall createMockHttpFirewall(MockHttpServletRequest request, FirewalledRequest fwr) {
HttpFirewall fw = mock(HttpFirewall.class);
given(fw.getFirewalledRequest(request)).willReturn(fwr);
return fw;
}
Test Case ID #spring-security_Test_66_2
Test Case Name: bothWrappersAreResetWithNestedFcps(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: fw
Suggested Diff
@@
// SEC-1639
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
- HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, this.fcp));
firstFcp.setFirewall(fw);
this.fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
+ HttpFirewall fw = createMockHttpFirewall(this.request, firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
}
@@
Original Test Code (click to expand)
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, this.fcp));
firstFcp.setFirewall(fw);
this.fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
}
Reusable Method for MCI (click to expand)
private static HttpFirewall createMockHttpFirewall(MockHttpServletRequest request, FirewalledRequest fwr) {
HttpFirewall fw = mock(HttpFirewall.class);
given(fw.getFirewalledRequest(request)).willReturn(fwr);
return fw;
}
Mock Clone Instance #spring-security_MCI_67
- Scope: class level
- Mocked Class:
org.springframework.security.acls.model.AclService
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockAclService {
public static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(), any())).willReturn(acl);
return service;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_67_1
Test Case Name: objectsAreRemovedIfPermissionDenied(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationCollectionFilteringProviderTests.java)
Mock Object Variable Name: service
Suggested Diff
@@
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(), any(), anyBoolean())).willReturn(false);
- given(service.readAclById(any(), any())).willReturn(acl);
+ AclService service = MockAclService.createMockAclService(acl);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(service, Arrays.asList(mock(Permission.class)));
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), new ArrayList(Arrays.asList(new Object(), new Object())));
assertThat(returned).isInstanceOf(List.class);
assertThat(((List) returned)).isEmpty();
returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "AFTER_ACL_COLLECTION_READ"), new Object[] { new Object(), new Object() });
assertThat(returned instanceof Object[]).isTrue();
assertThat(((Object[]) returned).length == 0).isTrue();
@@
Original Test Code (click to expand)
@Test
public void objectsAreRemovedIfPermissionDenied() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(), any(), anyBoolean())).willReturn(false);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationCollectionFilteringProvider provider = new AclEntryAfterInvocationCollectionFilteringProvider(service, Arrays.asList(mock(Permission.class)));
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_COLLECTION_READ"), new ArrayList(Arrays.asList(new Object(), new Object())));
assertThat(returned).isInstanceOf(List.class);
assertThat(((List) returned)).isEmpty();
returned = provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "AFTER_ACL_COLLECTION_READ"), new Object[] { new Object(), new Object() });
assertThat(returned instanceof Object[]).isTrue();
assertThat(((Object[]) returned).length == 0).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockAclService {
public static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(), any())).willReturn(acl);
return service;
}
}
Test Case ID #spring-security_Test_67_2
Test Case Name: accessIsAllowedIfPermissionIsGranted(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationProviderTests.java)
Mock Object Variable Name: service
Suggested Diff
@@
public void accessIsAllowedIfPermissionIsGranted() {
- AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true);
- given(service.readAclById(any(), any())).willReturn(acl);
+ AclService service = MockAclService.createMockAclService(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
Original Test Code (click to expand)
@Test
public void accessIsAllowedIfPermissionIsGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(true);
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Object returned = new Object();
assertThat(returned).isSameAs(provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("AFTER_ACL_READ"), returned));
}
Reusable Method for MCI (click to expand)
public class MockAclService {
public static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(), any())).willReturn(acl);
return service;
}
}
Test Case ID #spring-security_Test_67_3
Test Case Name: accessIsDeniedIfPermissionIsNotGranted(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\afterinvocation\AclEntryAfterInvocationProviderTests.java)
Mock Object Variable Name: service
Suggested Diff
@@
public void accessIsDeniedIfPermissionIsNotGranted() {
- AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false);
// Try a second time with no permissions found
given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException(""));
- given(service.readAclById(any(), any())).willReturn(acl);
+ AclService service = MockAclService.createMockAclService(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setProcessConfigAttribute("MY_ATTRIBUTE");
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
// Second scenario with no acls found
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
}
Original Test Code (click to expand)
@Test
public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class);
Acl acl = mock(Acl.class);
given(acl.isGranted(any(List.class), any(List.class), anyBoolean())).willReturn(false);
given(acl.isGranted(any(), any(List.class), anyBoolean())).willThrow(new NotFoundException(""));
given(service.readAclById(any(), any())).willReturn(acl);
AclEntryAfterInvocationProvider provider = new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
provider.setProcessConfigAttribute("MY_ATTRIBUTE");
provider.setMessageSource(new SpringSecurityMessageSource());
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(), SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
}
Reusable Method for MCI (click to expand)
public class MockAclService {
public static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(), any())).willReturn(acl);
return service;
}
}
Mock Clone Instance #spring-security_MCI_68
- Scope: method level
- Mocked Class:
org.springframework.security.acls.model.AclService
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
return service;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_68_1
Test Case Name: hasPermissionReturnsTrueIfAclGrantsPermission(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: service
Suggested Diff
@@
public void hasPermissionReturnsTrueIfAclGrantsPermission() {
- AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
+ AclService service = createMockAclService(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
@@
Original Test Code (click to expand)
@Test
public void hasPermissionReturnsTrueIfAclGrantsPermission() {
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
Reusable Method for MCI (click to expand)
private static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
return service;
}
Test Case ID #spring-security_Test_68_2
Test Case Name: resolvePermissionNonEnglishLocale(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: service
Suggested Diff
@@
Locale systemLocale = Locale.getDefault();
Locale.setDefault(new Locale("tr"));
- AclService service = mock(AclService.class);
+ AclService service = createMockAclService(acl);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
- given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
@@
Original Test Code (click to expand)
@Test
public void resolvePermissionNonEnglishLocale() {
Locale systemLocale = Locale.getDefault();
Locale.setDefault(new Locale("tr"));
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
}
Reusable Method for MCI (click to expand)
private static AclService createMockAclService(Acl acl) {
AclService service = mock(AclService.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
return service;
}
Mock Clone Instance #spring-security_MCI_69
- Scope: method level
- Mocked Class:
org.springframework.security.web.authentication.AuthenticationConverter
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthenticationConverter createMockAuthenticationConverter(HttpServletRequest request, Saml2AuthenticationToken token) {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(request)).willReturn(token);
return authenticationConverter;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_69_1
Test Case Name: attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\Saml2WebSsoAuthenticationFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
- AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
- given(authenticationConverter.convert(this.request)).willReturn(TestSaml2AuthenticationTokens.token());
+ AuthenticationConverter authenticationConverter = createMockAuthenticationConverter(this.request, TestSaml2AuthenticationTokens.token());
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.request.setRequestURI("/some/other/path/idp-registration-id");
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
this.filter.attemptAuthentication(this.request, this.response);
verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response);
@@
Original Test Code (click to expand)
@Test
public void attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(this.request)).willReturn(TestSaml2AuthenticationTokens.token());
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.request.setRequestURI("/some/other/path/idp-registration-id");
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
this.filter.attemptAuthentication(this.request, this.response);
verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response);
}
Reusable Method for MCI (click to expand)
private static AuthenticationConverter createMockAuthenticationConverter(HttpServletRequest request, Saml2AuthenticationToken token) {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(request)).willReturn(token);
return authenticationConverter;
}
Test Case ID #spring-security_Test_69_2
Test Case Name: attemptAuthenticationAddsDetails(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\Saml2WebSsoAuthenticationFilterTests.java)
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
@Test
public void attemptAuthenticationAddsDetails() {
- AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
final Saml2AuthenticationToken token = TestSaml2AuthenticationTokens.token();
- given(authenticationConverter.convert(this.request)).willReturn(token);
+ AuthenticationConverter authenticationConverter = createMockAuthenticationConverter(this.request, token);
final AuthenticationDetailsSource authenticationDetailsSource = mock(AuthenticationDetailsSource.class);
final WebAuthenticationDetails details = mock(WebAuthenticationDetails.class);
given(authenticationDetailsSource.buildDetails(this.request)).willReturn(details);
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.filter.setAuthenticationDetailsSource(authenticationDetailsSource);
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.attemptAuthentication(this.request, this.response);
assertThat(token.getDetails()).isEqualTo(details);
}
@@
Original Test Code (click to expand)
@Test
public void attemptAuthenticationAddsDetails() {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
final Saml2AuthenticationToken token = TestSaml2AuthenticationTokens.token();
given(authenticationConverter.convert(this.request)).willReturn(token);
final AuthenticationDetailsSource authenticationDetailsSource = mock(AuthenticationDetailsSource.class);
final WebAuthenticationDetails details = mock(WebAuthenticationDetails.class);
given(authenticationDetailsSource.buildDetails(this.request)).willReturn(details);
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.filter.setAuthenticationDetailsSource(authenticationDetailsSource);
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.attemptAuthentication(this.request, this.response);
assertThat(token.getDetails()).isEqualTo(details);
}
Reusable Method for MCI (click to expand)
private static AuthenticationConverter createMockAuthenticationConverter(HttpServletRequest request, Saml2AuthenticationToken token) {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(request)).willReturn(token);
return authenticationConverter;
}
Mock Clone Instance #spring-security_MCI_70
- Scope: method level
- Mocked Class:
org.springframework.security.web.authentication.AuthenticationConverter
- Test Case Count: 2
- MO Count: 2
Reusable Method
private AuthenticationConverter converter;
@BeforeEach
public void setUp() {
converter = mock(AuthenticationConverter.class);
}
converter;
The refactoring details in each test cases
Test Case ID #spring-security_Test_70_1
Mock Object Variable Name: converter
Suggested Diff
@@
@Test
public void getAuthenticationConverterWhenDuplicateConverterBeansAndAnotherOnTheDslThenTheDslOneIsUsed() {
- AuthenticationConverter converter = mock(AuthenticationConverter.class);
+ // removed local mock; replaced with global field `converter`
AuthenticationConverter converterBean = mock(AuthenticationConverter.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean("converterOne", AuthenticationConverter.class, () -> converterBean);
context.registerBean("converterTwo", AuthenticationConverter.class, () -> converterBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.authenticationConverter(converter);
assertThat(oauth2.getAuthenticationConverter()).isEqualTo(converter);
}
Original Test Code (click to expand)
@Test
public void getAuthenticationConverterWhenDuplicateConverterBeansAndAnotherOnTheDslThenTheDslOneIsUsed() {
AuthenticationConverter converter = mock(AuthenticationConverter.class);
AuthenticationConverter converterBean = mock(AuthenticationConverter.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean("converterOne", AuthenticationConverter.class, () -> converterBean);
context.registerBean("converterTwo", AuthenticationConverter.class, () -> converterBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.authenticationConverter(converter);
assertThat(oauth2.getAuthenticationConverter()).isEqualTo(converter);
}
Reusable Method for MCI (click to expand)
private AuthenticationConverter converter;
@BeforeEach
public void setUp() {
converter = mock(AuthenticationConverter.class);
}
converter;
Test Case ID #spring-security_Test_70_2
Mock Object Variable Name: converter
Suggested Diff
@@
@Test
public void getAuthenticationConverterWhenConverterBeanAndAnotherOnTheDslThenTheDslOneIsUsed() {
- AuthenticationConverter converter = mock(AuthenticationConverter.class);
+ // removed local mock; replaced with global field `converter`
AuthenticationConverter converterBean = mock(AuthenticationConverter.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(AuthenticationConverter.class, () -> converterBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.authenticationConverter(converter);
assertThat(oauth2.getAuthenticationConverter()).isEqualTo(converter);
}
Original Test Code (click to expand)
@Test
public void getAuthenticationConverterWhenConverterBeanAndAnotherOnTheDslThenTheDslOneIsUsed() {
AuthenticationConverter converter = mock(AuthenticationConverter.class);
AuthenticationConverter converterBean = mock(AuthenticationConverter.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(AuthenticationConverter.class, () -> converterBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.authenticationConverter(converter);
assertThat(oauth2.getAuthenticationConverter()).isEqualTo(converter);
}
Reusable Method for MCI (click to expand)
private AuthenticationConverter converter;
@BeforeEach
public void setUp() {
converter = mock(AuthenticationConverter.class);
}
converter;
Mock Clone Instance #spring-security_MCI_71
- Scope: method level
- Mocked Class:
org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServiceAuthenticationDetails createMockServiceAuthenticationDetails(String serviceUrl) {
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
return details;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_71_1
Test Case Name: authenticateAllNullService(File: C:\Java_projects\Spring\spring-security\cas\src\test\java\org\springframework\security\cas\authentication\CasAuthenticationProviderTests.java)
Mock Object Variable Name: details
Suggested Diff
@@
String serviceUrl = "https://service/context";
- ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
- given(details.getServiceUrl()).willReturn(serviceUrl);
+ ServiceAuthenticationDetails details = createMockServiceAuthenticationDetails(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
@@
Original Test Code (click to expand)
@Test
public void authenticateAllNullService() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket);
Authentication result = cap.authenticate(token);
}
Reusable Method for MCI (click to expand)
private static ServiceAuthenticationDetails createMockServiceAuthenticationDetails(String serviceUrl) {
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
return details;
}
Test Case ID #spring-security_Test_71_2
Test Case Name: authenticateAllAuthenticationIsSuccessful(File: C:\Java_projects\Spring\spring-security\cas\src\test\java\org\springframework\security\cas\authentication\CasAuthenticationProviderTests.java)
Mock Object Variable Name: details
Suggested Diff
@@
String serviceUrl = "https://service/context";
- ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
- given(details.getServiceUrl()).willReturn(serviceUrl);
+ ServiceAuthenticationDetails details = createMockServiceAuthenticationDetails(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
@@
Original Test Code (click to expand)
@Test
public void authenticateAllAuthenticationIsSuccessful() throws Exception {
String serviceUrl = "https://service/context";
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
TicketValidator validator = mock(TicketValidator.class);
given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod"));
ServiceProperties serviceProperties = makeServiceProperties();
serviceProperties.setAuthenticateAllArtifacts(true);
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
cap.setTicketValidator(validator);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
String ticket = "ST-456";
CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket);
Authentication result = cap.authenticate(token);
verify(validator).validate(ticket, serviceProperties.getService());
serviceProperties.setAuthenticateAllArtifacts(true);
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceProperties.getService());
token.setDetails(details);
result = cap.authenticate(token);
verify(validator).validate(ticket, serviceUrl);
serviceProperties.setAuthenticateAllArtifacts(false);
serviceProperties.setService(null);
cap.setServiceProperties(serviceProperties);
cap.afterPropertiesSet();
result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.setServiceProperties(null);
cap.afterPropertiesSet();
assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
}
Reusable Method for MCI (click to expand)
private static ServiceAuthenticationDetails createMockServiceAuthenticationDetails(String serviceUrl) {
ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class);
given(details.getServiceUrl()).willReturn(serviceUrl);
return details;
}
Mock Clone Instance #spring-security_MCI_72
- Scope: method level
- Mocked Class:
io.micrometer.observation.Observation
- Test Case Count: 4
- MO Count: 4
Reusable Method
private Observation observation;
@BeforeEach
public void setUp() {
observation = mock(Observation.class);
}
observation;
The refactoring details in each test cases
Test Case ID #spring-security_Test_72_1
Test Case Name: securityContextChangedWhenClearedEventThenAddsClearEventToObservation(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ObservationSecurityContextChangedListenerTests.java)
Mock Object Variable Name: observation
Suggested Diff
@@
@Test
void securityContextChangedWhenClearedEventThenAddsClearEventToObservation() {
- Observation observation = mock(Observation.class);
+ // removed local mock; replaced with global field `observation`
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
Supplier<SecurityContext> one = mock(Supplier.class);
this.tested.securityContextChanged(new SecurityContextChangedEvent(one, SecurityContextChangedEvent.NO_CONTEXT));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CLEARED);
verifyNoInteractions(one);
}
Original Test Code (click to expand)
@Test
void securityContextChangedWhenClearedEventThenAddsClearEventToObservation() {
Observation observation = mock(Observation.class);
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
Supplier<SecurityContext> one = mock(Supplier.class);
this.tested.securityContextChanged(new SecurityContextChangedEvent(one, SecurityContextChangedEvent.NO_CONTEXT));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CLEARED);
verifyNoInteractions(one);
}
Reusable Method for MCI (click to expand)
private Observation observation;
@BeforeEach
public void setUp() {
observation = mock(Observation.class);
}
observation;
Test Case ID #spring-security_Test_72_2
Test Case Name: securityContextChangedWhenNoChangeThenNoEventAddedToObservation(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ObservationSecurityContextChangedListenerTests.java)
Mock Object Variable Name: observation
Suggested Diff
@@
@Test
void securityContextChangedWhenNoChangeThenNoEventAddedToObservation() {
- Observation observation = mock(Observation.class);
+ // removed local mock; replaced with global field `observation`
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(this.one, this.one));
verifyNoInteractions(observation);
}
Original Test Code (click to expand)
@Test
void securityContextChangedWhenNoChangeThenNoEventAddedToObservation() {
Observation observation = mock(Observation.class);
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(this.one, this.one));
verifyNoInteractions(observation);
}
Reusable Method for MCI (click to expand)
private Observation observation;
@BeforeEach
public void setUp() {
observation = mock(Observation.class);
}
observation;
Test Case ID #spring-security_Test_72_3
Test Case Name: securityContextChangedWhenChangedEventThenAddsChangeEventToObservation(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ObservationSecurityContextChangedListenerTests.java)
Mock Object Variable Name: observation
Suggested Diff
@@
@Test
void securityContextChangedWhenChangedEventThenAddsChangeEventToObservation() {
- Observation observation = mock(Observation.class);
+ // removed local mock; replaced with global field `observation`
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(this.one, this.two));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CHANGED);
}
Original Test Code (click to expand)
@Test
void securityContextChangedWhenChangedEventThenAddsChangeEventToObservation() {
Observation observation = mock(Observation.class);
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(this.one, this.two));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CHANGED);
}
Reusable Method for MCI (click to expand)
private Observation observation;
@BeforeEach
public void setUp() {
observation = mock(Observation.class);
}
observation;
Test Case ID #spring-security_Test_72_4
Test Case Name: securityContextChangedWhenCreatedEventThenAddsCreatedEventToObservation(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ObservationSecurityContextChangedListenerTests.java)
Mock Object Variable Name: observation
Suggested Diff
@@
@Test
void securityContextChangedWhenCreatedEventThenAddsCreatedEventToObservation() {
- Observation observation = mock(Observation.class);
+ // removed local mock; replaced with global field `observation`
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(null, this.one));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CREATED);
}
Original Test Code (click to expand)
@Test
void securityContextChangedWhenCreatedEventThenAddsCreatedEventToObservation() {
Observation observation = mock(Observation.class);
given(this.observationRegistry.getCurrentObservation()).willReturn(observation);
this.tested.securityContextChanged(new SecurityContextChangedEvent(null, this.one));
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(observation).event(event.capture());
assertThat(event.getValue().getName()).isEqualTo(ObservationSecurityContextChangedListener.SECURITY_CONTEXT_CREATED);
}
Reusable Method for MCI (click to expand)
private Observation observation;
@BeforeEach
public void setUp() {
observation = mock(Observation.class);
}
observation;
Mock Clone Instance #spring-security_MCI_73
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.authorization.ServerAccessDeniedHandler
- Test Case Count: 3
- MO Count: 5
Reusable Method
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_73_1
Test Case Name: handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() {
- ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
+ ServerAccessDeniedHandler handler = createMockServerAccessDeniedHandler(this.exchange, Mono.empty());
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
- given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(matcher, handler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(this.accessDeniedHandler).handle(this.exchange, null);
verify(handler, never()).handle(this.exchange, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(matcher, handler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(this.accessDeniedHandler).handle(this.exchange, null);
verify(handler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
Test Case ID #spring-security_Test_73_2
Test Case Name: handleWhenFirstMatchesThenOnlyFirstInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstHandler
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
- given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
+ ServerAccessDeniedHandler firstHandler = createMockServerAccessDeniedHandler(this.exchange, Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
@@
Original Test Code (click to expand)
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(firstHandler).handle(this.exchange, null);
verify(secondHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
verify(secondMatcher, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
Test Case ID #spring-security_Test_73_3
Test Case Name: handleWhenFirstMatchesThenOnlyFirstInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: secondHandler
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
- ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
+ ServerAccessDeniedHandler secondHandler = createMockServerAccessDeniedHandler(this.exchange, Mono.empty());
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
- given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(firstHandler).handle(this.exchange, null);
verify(secondHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
verify(secondMatcher, never()).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(firstHandler).handle(this.exchange, null);
verify(secondHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
verify(secondMatcher, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
Test Case ID #spring-security_Test_73_4
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstHandler
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
- given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
+ ServerAccessDeniedHandler firstHandler = createMockServerAccessDeniedHandler(this.exchange, Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
Test Case ID #spring-security_Test_73_5
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: secondHandler
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
- ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
- given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
+ ServerAccessDeniedHandler secondHandler = createMockServerAccessDeniedHandler(this.exchange, Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerAccessDeniedHandler createMockServerAccessDeniedHandler(ServerWebExchange exchange, Mono<?> handleReturn) {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
given(handler.handle(exchange, null)).willReturn(handleReturn);
return handler;
}
Mock Clone Instance #spring-security_MCI_74
- Scope: method level
- Mocked Class:
org.springframework.security.web.context.SecurityContextRepository
- Test Case Count: 10
- MO Count: 10
Reusable Method
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
The refactoring details in each test cases
Test Case ID #spring-security_Test_74_1
Test Case Name: newSessionShouldNotBeCreatedIfSessionExistsAndUserIsNotAuthenticated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void newSessionShouldNotBeCreatedIfSessionExistsAndUserIsNotAuthenticated() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository);
HttpServletRequest request = new MockHttpServletRequest();
String sessionId = request.getSession().getId();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
assertThat(request.getSession().getId()).isEqualTo(sessionId);
}
Original Test Code (click to expand)
@Test
public void newSessionShouldNotBeCreatedIfSessionExistsAndUserIsNotAuthenticated() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionManagementFilter filter = new SessionManagementFilter(repo);
HttpServletRequest request = new MockHttpServletRequest();
String sessionId = request.getSession().getId();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
assertThat(request.getSession().getId()).isEqualTo(sessionId);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_2
Test Case Name: strategyIsNotInvokedIfAuthenticationIsNull(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
- SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
HttpServletRequest request = new MockHttpServletRequest();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Original Test Code (click to expand)
@Test
public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_3
Test Case Name: strategyIsInvokedIfUserIsNewlyAuthenticated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void strategyIsInvokedIfUserIsNewlyAuthenticated() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
// repo will return false to containsContext()
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
- SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
// Check that it is only applied once to the request
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Original Test Code (click to expand)
@Test
public void strategyIsInvokedIfUserIsNewlyAuthenticated() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_4
Test Case Name: strategyFailureInvokesFailureHandler(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void strategyFailureInvokesFailureHandler() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
// repo will return false to containsContext()
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
- SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
filter.setAuthenticationFailureHandler(failureHandler);
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
authenticateUser();
SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
verify(failureHandler).onAuthenticationFailure(request, response, exception);
}
Original Test Code (click to expand)
@Test
public void strategyFailureInvokesFailureHandler() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
filter.setAuthenticationFailureHandler(failureHandler);
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
authenticateUser();
SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
verify(failureHandler).onAuthenticationFailure(request, response, exception);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_5
Test Case Name: responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
// repo will return false to containsContext()
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
- SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
// Now set a redirect URL
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
SimpleRedirectInvalidSessionStrategy iss = new SimpleRedirectInvalidSessionStrategy("/timedOut");
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut");
}
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
SimpleRedirectInvalidSessionStrategy iss = new SimpleRedirectInvalidSessionStrategy("/timedOut");
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut");
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_6
Test Case Name: responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
// repo will return false to containsContext()
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
- SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
// Now set a redirect URL
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
RequestedUrlRedirectInvalidSessionStrategy iss = new RequestedUrlRedirectInvalidSessionStrategy();
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
RequestedUrlRedirectInvalidSessionStrategy iss = new RequestedUrlRedirectInvalidSessionStrategy();
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_7
Test Case Name: responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: securityContextRepository
Suggested Diff
@@
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
- SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
@@
// when
filter.doFilter(request, response, chain);
// then
- verify(securityContextRepository).containsContext(request);
+ verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(true);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/context/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_8
Test Case Name: responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: securityContextRepository
Suggested Diff
@@
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
- SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
@@
// then
- verify(securityContextRepository).containsContext(request);
+ verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_9
Test Case Name: customAuthenticationTrustResolver(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void customAuthenticationTrustResolver() throws Exception {
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS));
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionManagementFilter filter = new SessionManagementFilter(repo);
filter.setTrustResolver(trustResolver);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verify(trustResolver).isAnonymous(any(Authentication.class));
@@
- SessionManagementFilter filter = new SessionManagementFilter(repo);
+ SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository);
Original Test Code (click to expand)
@Test
public void customAuthenticationTrustResolver() throws Exception {
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS));
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionManagementFilter filter = new SessionManagementFilter(repo);
filter.setTrustResolver(trustResolver);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verify(trustResolver).isAnonymous(any(Authentication.class));
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Test Case ID #spring-security_Test_74_10
Test Case Name: setTrustResolverNull(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: repo
Suggested Diff
@@
@Test
public void setTrustResolverNull() {
- SecurityContextRepository repo = mock(SecurityContextRepository.class);
+ // removed local mock; replaced with global field `securityContextRepository`
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository);
assertThatIllegalArgumentException().isThrownBy(() -> filter.setTrustResolver(null));
}
Original Test Code (click to expand)
@Test
public void setTrustResolverNull() {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionManagementFilter filter = new SessionManagementFilter(repo);
assertThatIllegalArgumentException().isThrownBy(() -> filter.setTrustResolver(null));
}
Reusable Method for MCI (click to expand)
private SecurityContextRepository securityContextRepository;
@BeforeEach
public void setUp() {
securityContextRepository = mock(SecurityContextRepository.class);
}
securityContextRepository
Mock Clone Instance #spring-security_MCI_75
- Scope: method level
- Mocked Class:
org.springframework.security.web.context.SecurityContextRepository
- Test Case Count: 3
- MO Count: 6
Reusable Method
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_75_1
Test Case Name: loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() {
- SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
+ SecurityContextRepository delegate1 = createMockSecurityContextRepository(holder, securityContext1, false);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
- given(delegate1.loadContext(holder)).willReturn(securityContext1);
- given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Original Test Code (click to expand)
@Test
public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Test Case ID #spring-security_Test_75_2
Test Case Name: loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
- SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
+ SecurityContextRepository delegate2 = createMockSecurityContextRepository(holder, securityContext2, true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
@@
Original Test Code (click to expand)
@Test
public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Test Case ID #spring-security_Test_75_3
Test Case Name: loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
- SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
- given(delegate1.loadContext(holder)).willReturn(securityContext1);
- given(delegate1.containsContext(holder.getRequest())).willReturn(true);
+ SecurityContextRepository delegate1 = createMockSecurityContextRepository(holder, securityContext1, true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
@@
Original Test Code (click to expand)
@Test
public void loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Test Case ID #spring-security_Test_75_4
Test Case Name: loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
- SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
+ SecurityContextRepository delegate2 = createMockSecurityContextRepository(holder, securityContext2, true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
Original Test Code (click to expand)
@Test
public void loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Test Case ID #spring-security_Test_75_5
Test Case Name: loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
- SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
- given(delegate1.loadContext(holder)).willReturn(securityContext1);
- given(delegate1.containsContext(holder.getRequest())).willReturn(true);
+ SecurityContextRepository delegate1 = createMockSecurityContextRepository(holder, securityContext1, true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
}
@@
Original Test Code (click to expand)
@Test
public void loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Test Case ID #spring-security_Test_75_6
Test Case Name: loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
- SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
+ SecurityContextRepository delegate2 = createMockSecurityContextRepository(holder, securityContext2, false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
Original Test Code (click to expand)
@Test
public void loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
}
Reusable Method for MCI (click to expand)
private static SecurityContextRepository createMockSecurityContextRepository(HttpRequestResponseHolder holder, SecurityContext securityContext, boolean containsContext) {
SecurityContextRepository mockRepository = mock(SecurityContextRepository.class);
given(mockRepository.loadContext(holder)).willReturn(securityContext);
given(mockRepository.containsContext(holder.getRequest())).willReturn(containsContext);
return mockRepository;
}
Mock Clone Instance #spring-security_MCI_76
- Scope: class level
- Mocked Class:
io.rsocket.ConnectionSetupPayload
- Test Case Count: 6
- MO Count: 6
Reusable Method
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_76_1
Mock Object Variable Name: setupPayload
Suggested Diff
@@
@Test
public void applyWhenDefaultMetadataMimeTypeThenDefaulted() {
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString()).isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Original Test Code (click to expand)
@Test
public void applyWhenDefaultMetadataMimeTypeThenDefaulted() {
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString()).isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Test Case ID #spring-security_Test_76_2
Mock Object Variable Name: setupPayload
Suggested Diff
@@
this.acceptorInterceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Original Test Code (click to expand)
@Test
public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() {
this.acceptorInterceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Test Case ID #spring-security_Test_76_3
Mock Object Variable Name: setupPayload
Suggested Diff
@@
@Test
public void acceptWhenDefaultMetadataMimeTypeThenDefaulted() {
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString()).isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Original Test Code (click to expand)
@Test
public void acceptWhenDefaultMetadataMimeTypeThenDefaulted() {
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType().toString()).isEqualTo(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Test Case ID #spring-security_Test_76_4
Mock Object Variable Name: setupPayload
Suggested Diff
@@
this.acceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
Original Test Code (click to expand)
@Test
public void acceptWhenDefaultMetadataMimeTypeOverrideThenDefaulted() {
this.acceptor.setDefaultMetadataMimeType(MediaType.APPLICATION_JSON);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Test Case ID #spring-security_Test_76_5
Test Case Name: acceptWhenExplicitMimeTypeThenThenOverrideDefault(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadSocketAcceptorTests.java)
Mock Object Variable Name: setupPayload
Suggested Diff
@@
@Test
public void acceptWhenExplicitMimeTypeThenThenOverrideDefault() {
- given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
+ given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
@@
Original Test Code (click to expand)
@Test
public void acceptWhenExplicitMimeTypeThenThenOverrideDefault() {
given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
PayloadExchange exchange = captureExchange();
assertThat(exchange.getMetadataMimeType()).isEqualTo(MediaType.TEXT_PLAIN);
assertThat(exchange.getDataMimeType()).isEqualTo(MediaType.APPLICATION_JSON);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Test Case ID #spring-security_Test_76_6
Test Case Name: acceptWhenDelegateAcceptRequiresReactiveSecurityContext(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadSocketAcceptorTests.java)
Mock Object Variable Name: setupPayload
Suggested Diff
@@
@Test
public // gh-8654
void acceptWhenDelegateAcceptRequiresReactiveSecurityContext() {
- given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
- given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
+ this.setupPayload = MockConnectionSetupPayload.createMockConnectionSetupPayload(MediaType.APPLICATION_JSON_VALUE);
+ given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
SecurityContext expectedSecurityContext = new SecurityContextImpl(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
CaptureSecurityContextSocketAcceptor captureSecurityContext = new CaptureSecurityContextSocketAcceptor(this.rSocket);
PayloadInterceptor authenticateInterceptor = (exchange, chain) -> {
Context withSecurityContext = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedSecurityContext));
return chain.next(exchange).contextWrite(withSecurityContext);
};
List<PayloadInterceptor> interceptors = Arrays.asList(authenticateInterceptor);
this.acceptor = new PayloadSocketAcceptor(captureSecurityContext, interceptors);
this.acceptor.accept(this.setupPayload, this.rSocket).block();
assertThat(captureSecurityContext.getSecurityContext()).isEqualTo(expectedSecurityContext);
}
@@
Original Test Code (click to expand)
@Test
public
void acceptWhenDelegateAcceptRequiresReactiveSecurityContext() {
given(this.setupPayload.metadataMimeType()).willReturn(MediaType.TEXT_PLAIN_VALUE);
given(this.setupPayload.dataMimeType()).willReturn(MediaType.APPLICATION_JSON_VALUE);
SecurityContext expectedSecurityContext = new SecurityContextImpl(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
CaptureSecurityContextSocketAcceptor captureSecurityContext = new CaptureSecurityContextSocketAcceptor(this.rSocket);
PayloadInterceptor authenticateInterceptor = (exchange, chain) -> {
Context withSecurityContext = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(expectedSecurityContext));
return chain.next(exchange).contextWrite(withSecurityContext);
};
List<PayloadInterceptor> interceptors = Arrays.asList(authenticateInterceptor);
this.acceptor = new PayloadSocketAcceptor(captureSecurityContext, interceptors);
this.acceptor.accept(this.setupPayload, this.rSocket).block();
assertThat(captureSecurityContext.getSecurityContext()).isEqualTo(expectedSecurityContext);
}
Reusable Method for MCI (click to expand)
public class MockConnectionSetupPayload {
public static ConnectionSetupPayload createMockConnectionSetupPayload(String dataMimeTypeReturn) {
ConnectionSetupPayload setupPayload = Mockito.mock(ConnectionSetupPayload.class);
given(setupPayload.dataMimeType()).willReturn(dataMimeTypeReturn);
return setupPayload;
}
}
Mock Clone Instance #spring-security_MCI_77
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.AuthenticationEventPublisher
- Test Case Count: 6
- MO Count: 6
Reusable Method
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
The refactoring details in each test cases
Test Case ID #spring-security_Test_77_1
Test Case Name: authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
@Test
void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(createProviderWhichReturns(a));
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isEqualTo(a);
- verify(publisher).publishAuthenticationSuccess(result);
+ verify(publisher).publishAuthenticationSuccess(result);
}
Original Test Code (click to expand)
@Test
void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(createProviderWhichReturns(a));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isEqualTo(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Test Case ID #spring-security_Test_77_2
Test Case Name: authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
@Test
void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isSameAs(a);
- verify(publisher).publishAuthenticationSuccess(result);
+ verify(publisher).publishAuthenticationSuccess(result);
}
Original Test Code (click to expand)
@Test
void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isSameAs(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Test Case ID #spring-security_Test_77_3
Test Case Name: providerNotFoundFromParentIsIgnored(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
@Test
void providerNotFoundFromParentIsIgnored() {
final Authentication authReq = mock(Authentication.class);
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
AuthenticationManager parent = mock(AuthenticationManager.class);
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
- mgr.setAuthenticationEventPublisher(publisher);
+ mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
}
Original Test Code (click to expand)
@Test
void providerNotFoundFromParentIsIgnored() {
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Test Case ID #spring-security_Test_77_4
Test Case Name: authenticationExceptionFromParentOverridesPreviousOnes(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
@Test
void authenticationExceptionFromParentOverridesPreviousOnes() {
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
Authentication authReq = mock(Authentication.class);
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
given(parent.authenticate(authReq)).willThrow(expected);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).isSameAs(expected);
}
Original Test Code (click to expand)
@Test
void authenticationExceptionFromParentOverridesPreviousOnes() {
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
given(parent.authenticate(authReq)).willThrow(expected);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).isSameAs(expected);
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Test Case ID #spring-security_Test_77_5
Test Case Name: statusExceptionIsPublished(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
@Test
void statusExceptionIsPublished() {
AuthenticationManager parent = mock(AuthenticationManager.class);
LockedException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(expected)), parent);
Authentication authReq = mock(Authentication.class);
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
- verify(publisher).publishAuthenticationFailure(expected, authReq);
+ verify(publisher).publishAuthenticationFailure(expected, authReq);
}
Original Test Code (click to expand)
@Test
void statusExceptionIsPublished() {
AuthenticationManager parent = mock(AuthenticationManager.class);
LockedException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(expected)), parent);
Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Test Case ID #spring-security_Test_77_6
Test Case Name: authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: publisher
Suggested Diff
@@
void authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish() {
BadCredentialsException badCredentialsExParent = new BadCredentialsException("Bad Credentials in parent");
ProviderManager parentMgr = new ProviderManager(createProviderWhichThrows(badCredentialsExParent));
ProviderManager childMgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException("Bad Credentials in child"))), parentMgr);
- AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
+ // removed local mock; replaced with global field `publisher`
parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher);
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq)).isSameAs(badCredentialsExParent);
// Parent
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq);
// publishes
// Child should not publish (duplicate event)
verifyNoMoreInteractions(publisher);
}
Original Test Code (click to expand)
@Test
void authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish() {
BadCredentialsException badCredentialsExParent = new BadCredentialsException("Bad Credentials in parent");
ProviderManager parentMgr = new ProviderManager(createProviderWhichThrows(badCredentialsExParent));
ProviderManager childMgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException("Bad Credentials in child"))), parentMgr);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher);
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq)).isSameAs(badCredentialsExParent);
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq);
verifyNoMoreInteractions(publisher);
}
Reusable Method for MCI (click to expand)
private AuthenticationEventPublisher publisher;
@BeforeEach
public void setUp() {
publisher = mock(AuthenticationEventPublisher.class);
}
publisher;
Mock Clone Instance #spring-security_MCI_78
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.core.oidc.user.OidcUser
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static OidcUser createMockOidcUserWithAuthorities(Answer<List<GrantedAuthority>> authoritiesAnswer) {
OidcUser principal = mock(OidcUser.class);
given(principal.getAuthorities()).willAnswer(authoritiesAnswer);
return principal;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_78_1
Test Case Name: authenticateWhenLoginSuccessThenReturnAuthentication(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
this.setUpIdToken(claims);
- OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OidcUser principal = createMockOidcUserWithAuthorities((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.isAuthenticated()).isTrue();
assertThat(authentication.getPrincipal()).isEqualTo(principal);
assertThat(authentication.getCredentials()).isEqualTo("");
assertThat(authentication.getAuthorities()).isEqualTo(authorities);
assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
assertThat(authentication.getAccessToken()).isEqualTo(this.accessTokenResponse.getAccessToken());
assertThat(authentication.getRefreshToken()).isEqualTo(this.accessTokenResponse.getRefreshToken());
}
Reusable Method for MCI (click to expand)
private static OidcUser createMockOidcUserWithAuthorities(Answer<List<GrantedAuthority>> authoritiesAnswer) {
OidcUser principal = mock(OidcUser.class);
given(principal.getAuthorities()).willAnswer(authoritiesAnswer);
return principal;
}
Test Case ID #spring-security_Test_78_2
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
- OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OidcUser principal = createMockOidcUserWithAuthorities((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
private static OidcUser createMockOidcUserWithAuthorities(Answer<List<GrantedAuthority>> authoritiesAnswer) {
OidcUser principal = mock(OidcUser.class);
given(principal.getAuthorities()).willAnswer(authoritiesAnswer);
return principal;
}
Test Case ID #spring-security_Test_78_3
Test Case Name: authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProviderTests.java)
Mock Object Variable Name: principal
Suggested Diff
@@
this.setUpIdToken(claims);
- OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
- given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
+ OidcUser principal = createMockOidcUserWithAuthorities((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(this.accessTokenResponse.getAdditionalParameters());
Original Test Code (click to expand)
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(this.accessTokenResponse.getAdditionalParameters());
}
Reusable Method for MCI (click to expand)
private static OidcUser createMockOidcUserWithAuthorities(Answer<List<GrantedAuthority>> authoritiesAnswer) {
OidcUser principal = mock(OidcUser.class);
given(principal.getAuthorities()).willAnswer(authoritiesAnswer);
return principal;
}
Mock Clone Instance #spring-security_MCI_79
- Scope: method level
- Mocked Class:
org.springframework.core.convert.converter.Converter<java.lang.Object, java.lang.String>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Converter<Object, String> createMockClaimConverter() {
Converter<Object, String> claimConverter = mock(Converter.class);
given(claimConverter.convert(any(Object.class))).willReturn("1234");
return claimConverter;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_79_1
Test Case Name: convertWhenUsingCustomConverterThenAllOtherDefaultsAreStillUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\MappedJwtClaimSetConverterTests.java)
Mock Object Variable Name: claimConverter
Suggested Diff
@@
@Test
public void convertWhenUsingCustomConverterThenAllOtherDefaultsAreStillUsed() {
- Converter<Object, String> claimConverter = mock(Converter.class);
+ Converter<Object, String> claimConverter = createMockClaimConverter();
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
- given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, 1);
source.put(JwtClaimNames.AUD, "audience");
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
source.put(JwtClaimNames.IAT, new Date(1000000000000L));
source.put(JwtClaimNames.ISS, URI.create("https://any.url"));
source.put(JwtClaimNames.NBF, "1000000000");
source.put(JwtClaimNames.SUB, 2345);
Map<String, Object> target = converter.convert(source);
assertThat(target).containsEntry(JwtClaimNames.JTI, "1");
assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("audience"));
assertThat(target).containsEntry(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1000000000L));
assertThat(target).containsEntry(JwtClaimNames.ISS, "https://any.url");
assertThat(target).containsEntry(JwtClaimNames.NBF, Instant.ofEpochSecond(1000000000L));
assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenUsingCustomConverterThenAllOtherDefaultsAreStillUsed() {
Converter<Object, String> claimConverter = mock(Converter.class);
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, 1);
source.put(JwtClaimNames.AUD, "audience");
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
source.put(JwtClaimNames.IAT, new Date(1000000000000L));
source.put(JwtClaimNames.ISS, URI.create("https://any.url"));
source.put(JwtClaimNames.NBF, "1000000000");
source.put(JwtClaimNames.SUB, 2345);
Map<String, Object> target = converter.convert(source);
assertThat(target).containsEntry(JwtClaimNames.JTI, "1");
assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("audience"));
assertThat(target).containsEntry(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1000000000L));
assertThat(target).containsEntry(JwtClaimNames.ISS, "https://any.url");
assertThat(target).containsEntry(JwtClaimNames.NBF, Instant.ofEpochSecond(1000000000L));
assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
}
Reusable Method for MCI (click to expand)
private static Converter<Object, String> createMockClaimConverter() {
Converter<Object, String> claimConverter = mock(Converter.class);
given(claimConverter.convert(any(Object.class))).willReturn("1234");
return claimConverter;
}
Test Case ID #spring-security_Test_79_2
Test Case Name: convertWhenUsingConstructorThenOnlyConvertersInThatMapAreUsedForConversion(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\MappedJwtClaimSetConverterTests.java)
Mock Object Variable Name: claimConverter
Suggested Diff
@@
public void convertWhenUsingConstructorThenOnlyConvertersInThatMapAreUsedForConversion() {
- Converter<Object, String> claimConverter = mock(Converter.class);
+ Converter<Object, String> claimConverter = createMockClaimConverter();
MappedJwtClaimSetConverter converter = new MappedJwtClaimSetConverter(Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
- given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, new Object());
source.put(JwtClaimNames.AUD, new Object());
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.IAT, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.ISS, new Object());
source.put(JwtClaimNames.NBF, new Object());
source.put(JwtClaimNames.SUB, new Object());
Map<String, Object> target = converter.convert(source);
assertThat(target).containsEntry(JwtClaimNames.JTI, source.get(JwtClaimNames.JTI));
assertThat(target).containsEntry(JwtClaimNames.AUD, source.get(JwtClaimNames.AUD));
assertThat(target).containsEntry(JwtClaimNames.EXP, source.get(JwtClaimNames.EXP));
assertThat(target).containsEntry(JwtClaimNames.IAT, source.get(JwtClaimNames.IAT));
assertThat(target).containsEntry(JwtClaimNames.ISS, source.get(JwtClaimNames.ISS));
assertThat(target).containsEntry(JwtClaimNames.NBF, source.get(JwtClaimNames.NBF));
assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
}
Original Test Code (click to expand)
@Test
public void convertWhenUsingConstructorThenOnlyConvertersInThatMapAreUsedForConversion() {
Converter<Object, String> claimConverter = mock(Converter.class);
MappedJwtClaimSetConverter converter = new MappedJwtClaimSetConverter(Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, new Object());
source.put(JwtClaimNames.AUD, new Object());
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.IAT, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.ISS, new Object());
source.put(JwtClaimNames.NBF, new Object());
source.put(JwtClaimNames.SUB, new Object());
Map<String, Object> target = converter.convert(source);
assertThat(target).containsEntry(JwtClaimNames.JTI, source.get(JwtClaimNames.JTI));
assertThat(target).containsEntry(JwtClaimNames.AUD, source.get(JwtClaimNames.AUD));
assertThat(target).containsEntry(JwtClaimNames.EXP, source.get(JwtClaimNames.EXP));
assertThat(target).containsEntry(JwtClaimNames.IAT, source.get(JwtClaimNames.IAT));
assertThat(target).containsEntry(JwtClaimNames.ISS, source.get(JwtClaimNames.ISS));
assertThat(target).containsEntry(JwtClaimNames.NBF, source.get(JwtClaimNames.NBF));
assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
}
Reusable Method for MCI (click to expand)
private static Converter<Object, String> createMockClaimConverter() {
Converter<Object, String> claimConverter = mock(Converter.class);
given(claimConverter.convert(any(Object.class))).willReturn("1234");
return claimConverter;
}
Mock Clone Instance #spring-security_MCI_80
- Scope: method level
- Mocked Class:
org.springframework.security.core.userdetails.UserDetailsService
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static UserDetailsService createMockUserDetailsService(UserDetails user) {
UserDetailsService userDetailsService = mock(UserDetailsService.class);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
return userDetailsService;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_80_1
Test Case Name: authenticateWhenSuccessAndPasswordManagerThenUpdates(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
PasswordEncoder encoder = mock(PasswordEncoder.class);
- UserDetailsService userDetailsService = mock(UserDetailsService.class);
+ UserDetailsService userDetailsService = createMockUserDetailsService(user);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(true);
given(encoder.encode(any())).willReturn(encodedPassword);
- given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
verify(encoder).encode(password);
verify(passwordManager).updatePassword(eq(user), eq(encodedPassword));
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenSuccessAndPasswordManagerThenUpdates() {
String password = "password";
String encodedPassword = "encoded";
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", password);
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(true);
given(encoder.encode(any())).willReturn(encodedPassword);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
verify(encoder).encode(password);
verify(passwordManager).updatePassword(eq(user), eq(encodedPassword));
}
Reusable Method for MCI (click to expand)
private static UserDetailsService createMockUserDetailsService(UserDetails user) {
UserDetailsService userDetailsService = mock(UserDetailsService.class);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
return userDetailsService;
}
Test Case ID #spring-security_Test_80_2
Test Case Name: authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
PasswordEncoder encoder = mock(PasswordEncoder.class);
- UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(false);
- given(userDetailsService.loadUserByUsername(any())).willReturn(user);
+ UserDetailsService userDetailsService = createMockUserDetailsService(user);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
verifyNoMoreInteractions(passwordManager);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
verifyNoMoreInteractions(passwordManager);
}
Reusable Method for MCI (click to expand)
private static UserDetailsService createMockUserDetailsService(UserDetails user) {
UserDetailsService userDetailsService = mock(UserDetailsService.class);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
return userDetailsService;
}
Test Case ID #spring-security_Test_80_3
Test Case Name: authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
PasswordEncoder encoder = mock(PasswordEncoder.class);
- UserDetailsService userDetailsService = mock(UserDetailsService.class);
+ UserDetailsService userDetailsService = createMockUserDetailsService(user);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(false);
- given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
verifyNoMoreInteractions(passwordManager);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
verifyNoMoreInteractions(passwordManager);
}
Reusable Method for MCI (click to expand)
private static UserDetailsService createMockUserDetailsService(UserDetails user) {
UserDetailsService userDetailsService = mock(UserDetailsService.class);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
return userDetailsService;
}
Mock Clone Instance #spring-security_MCI_81
- Scope: method level
- Mocked Class:
org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
- Test Case Count: 7
- MO Count: 7
Reusable Method
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
The refactoring details in each test cases
Test Case ID #spring-security_Test_81_1
Test Case Name: strategyIsNotInvokedIfSecurityContextAlreadyExistsForRequest(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void strategyIsNotInvokedIfSecurityContextAlreadyExistsForRequest() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
- SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
// mock that repo contains a security context
given(repo.containsContext(any(HttpServletRequest.class))).willReturn(true);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
- verifyNoMoreInteractions(strategy);
+ verifyNoMoreInteractions(strategy);
}
Original Test Code (click to expand)
@Test
public void strategyIsNotInvokedIfSecurityContextAlreadyExistsForRequest() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
given(repo.containsContext(any(HttpServletRequest.class))).willReturn(true);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_2
Test Case Name: strategyIsNotInvokedIfAuthenticationIsNull(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
- SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
- verifyNoMoreInteractions(strategy);
+ verifyNoMoreInteractions(strategy);
}
Original Test Code (click to expand)
@Test
public void strategyIsNotInvokedIfAuthenticationIsNull() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_3
Test Case Name: strategyIsInvokedIfUserIsNewlyAuthenticated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void strategyIsInvokedIfUserIsNewlyAuthenticated() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
// repo will return false to containsContext()
- SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
- verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
// Check that it is only applied once to the request
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
- verifyNoMoreInteractions(strategy);
+ verifyNoMoreInteractions(strategy);
}
Original Test Code (click to expand)
@Test
public void strategyIsInvokedIfUserIsNewlyAuthenticated() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
HttpServletRequest request = new MockHttpServletRequest();
authenticateUser();
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verify(strategy).onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyNoMoreInteractions(strategy);
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_4
Test Case Name: responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
// repo will return false to containsContext()
- SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
SimpleRedirectInvalidSessionStrategy iss = new SimpleRedirectInvalidSessionStrategy("/timedOut");
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut");
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_5
Test Case Name: responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
// repo will return false to containsContext()
- SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
RequestedUrlRedirectInvalidSessionStrategy iss = new RequestedUrlRedirectInvalidSessionStrategy();
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_6
Test Case Name: responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: sessionAuthenticationStrategy
Suggested Diff
@@
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
- SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, strategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
@@
// then
verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, strategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(true);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/context/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Test Case ID #spring-security_Test_81_7
Test Case Name: responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: sessionAuthenticationStrategy
Suggested Diff
@@
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
- SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
+ // removed local mock; replaced with global field `strategy`
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
@@
FilterChain chain = mock(FilterChain.class);
// when
filter.doFilter(request, response, chain);
// then
verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, strategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
Reusable Method for MCI (click to expand)
private SessionAuthenticationStrategy strategy;
@BeforeEach
public void setUp() {
strategy = mock(SessionAuthenticationStrategy.class);
}
strategy;
Mock Clone Instance #spring-security_MCI_82
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.AuthorizationManager<jakarta.servlet.http.HttpServletRequest>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static AuthorizationManager<HttpServletRequest> createMockAuthorizationManagerWithAuthorizeRealMethod() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_82_1
Test Case Name: filterWhenAuthorizationManagerVerifyPassesThenNextFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockAuthorizationManager
Suggested Diff
@@
@Test
public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception {
- AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
- given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<HttpServletRequest> mockAuthorizationManager = createMockAuthorizationManagerWithAuthorizeRealMethod();
given(mockAuthorizationManager.check(any(Supplier.class), any(HttpServletRequest.class))).willReturn(new AuthorizationDecision(true));
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authenticationToken));
filter.setSecurityContextHolderStrategy(strategy);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
filter.doFilter(mockRequest, mockResponse, mockFilterChain);
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verify(mockFilterChain).doFilter(mockRequest, mockResponse);
verify(strategy).getContext();
}
@@
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
given(mockAuthorizationManager.check(any(Supplier.class), any(HttpServletRequest.class))).willReturn(new AuthorizationDecision(true));
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authenticationToken));
filter.setSecurityContextHolderStrategy(strategy);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
filter.doFilter(mockRequest, mockResponse, mockFilterChain);
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verify(mockFilterChain).doFilter(mockRequest, mockResponse);
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<HttpServletRequest> createMockAuthorizationManagerWithAuthorizeRealMethod() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Test Case ID #spring-security_Test_82_2
Test Case Name: filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockAuthorizationManager
Suggested Diff
@@
public void filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain() {
- AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
- given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<HttpServletRequest> mockAuthorizationManager = createMockAuthorizationManagerWithAuthorizeRealMethod();
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authenticationToken);
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(), eq(mockRequest));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("Access Denied");
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verifyNoInteractions(mockFilterChain);
@@
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authenticationToken);
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(), eq(mockRequest));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("Access Denied");
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verifyNoInteractions(mockFilterChain);
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<HttpServletRequest> createMockAuthorizationManagerWithAuthorizeRealMethod() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Test Case ID #spring-security_Test_82_3
Test Case Name: doFilterWhenErrorThenDoFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: authorizationManager
Suggested Diff
@@
public void doFilterWhenErrorThenDoFilter() throws Exception {
- AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
- given(authorizationManager.authorize(any(), any())).willCallRealMethod();
+ AuthorizationManager<HttpServletRequest> authorizationManager = createMockAuthorizationManagerWithAuthorizeRealMethod();
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(authorizationManager).check(any(Supplier.class), eq(mockRequest));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenErrorThenDoFilter() throws Exception {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
given(authorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(authorizationManager).check(any(Supplier.class), eq(mockRequest));
}
Reusable Method for MCI (click to expand)
private static AuthorizationManager<HttpServletRequest> createMockAuthorizationManagerWithAuthorizeRealMethod() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_83
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.AuthorizationManager<jakarta.servlet.http.HttpServletRequest>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private AuthorizationManager<HttpServletRequest> authorizationManager;
@BeforeEach
public void setUp() {
authorizationManager = mock(AuthorizationManager.class);
}
authorizationManager
The refactoring details in each test cases
Test Case ID #spring-security_Test_83_1
Test Case Name: getAuthorizationManager(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: authorizationManager
Suggested Diff
@@
@Test
public void getAuthorizationManager() {
- AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
+ // removed local mock; replaced with global field `authorizationManager`
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
@@
- assertThat(authorizationFilter.getAuthorizationManager()).isSameAs(authorizationManager);
+ assertThat(authorizationFilter.getAuthorizationManager()).isSameAs(authorizationManager);
}
Original Test Code (click to expand)
@Test
public void getAuthorizationManager() {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
assertThat(authorizationFilter.getAuthorizationManager()).isSameAs(authorizationManager);
}
Reusable Method for MCI (click to expand)
private AuthorizationManager<HttpServletRequest> authorizationManager;
@BeforeEach
public void setUp() {
authorizationManager = mock(AuthorizationManager.class);
}
authorizationManager
Test Case ID #spring-security_Test_83_2
Mock Object Variable Name: authorizationManager
Suggested Diff
@@
@Test
public void configureWhenAuthorizationEventPublisherIsNullThenIllegalArgument() {
- AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
+ // removed local mock; replaced with global field `authorizationManager`
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
assertThatIllegalArgumentException().isThrownBy(() -> authorizationFilter.setAuthorizationEventPublisher(null)).withMessage("eventPublisher cannot be null");
}
Original Test Code (click to expand)
@Test
public void configureWhenAuthorizationEventPublisherIsNullThenIllegalArgument() {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
assertThatIllegalArgumentException().isThrownBy(() -> authorizationFilter.setAuthorizationEventPublisher(null)).withMessage("eventPublisher cannot be null");
}
Reusable Method for MCI (click to expand)
private AuthorizationManager<HttpServletRequest> authorizationManager;
@BeforeEach
public void setUp() {
authorizationManager = mock(AuthorizationManager.class);
}
authorizationManager
Test Case ID #spring-security_Test_83_3
Test Case Name: doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: authorizationManager
Suggested Diff
@@
@Test
public void doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter() throws Exception {
- AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
+ // removed local mock; replaced with global field `authorizationManager`
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
authorizationFilter.setShouldFilterAllDispatcherTypes(false);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
- verifyNoInteractions(authorizationManager);
+ verifyNoInteractions(authorizationManager);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter() throws Exception {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
authorizationFilter.setShouldFilterAllDispatcherTypes(false);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verifyNoInteractions(authorizationManager);
}
Reusable Method for MCI (click to expand)
private AuthorizationManager<HttpServletRequest> authorizationManager;
@BeforeEach
public void setUp() {
authorizationManager = mock(AuthorizationManager.class);
}
authorizationManager
Mock Clone Instance #spring-security_MCI_84
- Scope: class level
- Mocked Class:
org.springframework.web.reactive.function.client.WebClient
- Test Case Count: 3
- MO Count: 4
Reusable Method
public class MockWebClient {
public static WebClient createMockWebClient() {
WebClient mockWebClient = mock();
given(mockWebClient.post()).willReturn(WebClient.builder().build().post());
return mockWebClient;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_84_1
Test Case Name: setCustomWebClientThenCustomWebClientIsUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveAuthorizationCodeTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
public void setCustomWebClientThenCustomWebClientIsUsed() {
- WebClient customClient = mock();
- given(customClient.post()).willReturn(WebClient.builder().build().post());
+ WebClient customClient = MockWebClient.createMockWebClient();
this.tokenResponseClient.setWebClient(customClient);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.clientRegistration.scope("openid", "profile", "email", "address");
OAuth2AccessTokenResponse response = this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block();
verify(customClient, atLeastOnce()).post();
}
Original Test Code (click to expand)
@Test
public void setCustomWebClientThenCustomWebClientIsUsed() {
WebClient customClient = mock();
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.tokenResponseClient.setWebClient(customClient);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.clientRegistration.scope("openid", "profile", "email", "address");
OAuth2AccessTokenResponse response = this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block();
verify(customClient, atLeastOnce()).post();
}
Reusable Method for MCI (click to expand)
public class MockWebClient {
public static WebClient createMockWebClient() {
WebClient mockWebClient = mock();
given(mockWebClient.post()).willReturn(WebClient.builder().build().post());
return mockWebClient;
}
}
Test Case ID #spring-security_Test_84_2
Test Case Name: setWebClientCustomThenCustomClientIsUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
public void setWebClientCustomThenCustomClientIsUsed() {
- WebClient customClient = mock();
- given(customClient.post()).willReturn(WebClient.builder().build().post());
+ WebClient customClient = MockWebClient.createMockWebClient();
this.client.setWebClient(customClient);
ClientRegistration registration = this.clientRegistration.build();
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
verify(customClient, atLeastOnce()).post();
}
Original Test Code (click to expand)
@Test
public void setWebClientCustomThenCustomClientIsUsed() {
WebClient customClient = mock();
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.client.setWebClient(customClient);
ClientRegistration registration = this.clientRegistration.build();
this.server.enqueue(MockResponses.json("access-token-response.json"));
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
OAuth2AccessTokenResponse response = this.client.getTokenResponse(request).block();
verify(customClient, atLeastOnce()).post();
}
Reusable Method for MCI (click to expand)
public class MockWebClient {
public static WebClient createMockWebClient() {
WebClient mockWebClient = mock();
given(mockWebClient.post()).willReturn(WebClient.builder().build().post());
return mockWebClient;
}
}
Test Case ID #spring-security_Test_84_3
Test Case Name: getTokenResponseWhenWebClientSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
public void getTokenResponseWhenWebClientSetThenCalled() {
- WebClient customClient = mock();
- given(customClient.post()).willReturn(WebClient.builder().build().post());
+ WebClient customClient = MockWebClient.createMockWebClient();
this.client.setWebClient(customClient);
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration registration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
this.client.getTokenResponse(request).block();
verify(customClient).post();
}
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenWebClientSetThenCalled() {
WebClient customClient = mock();
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.client.setWebClient(customClient);
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration registration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(registration, this.jwtAssertion);
this.client.getTokenResponse(request).block();
verify(customClient).post();
}
Reusable Method for MCI (click to expand)
public class MockWebClient {
public static WebClient createMockWebClient() {
WebClient mockWebClient = mock();
given(mockWebClient.post()).willReturn(WebClient.builder().build().post());
return mockWebClient;
}
}
Test Case ID #spring-security_Test_84_4
Test Case Name: getTokenResponseWhenWebClientSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: customClient
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
- WebClient customClient = mock();
- given(customClient.post()).willReturn(WebClient.builder().build().post());
+ WebClient customClient = MockWebClient.createMockWebClient();
this.tokenResponseClient.setWebClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(customClient).post();
}
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenWebClientSetThenCalled() {
this.server.enqueue(MockResponses.json("access-token-response.json"));
WebClient customClient = mock();
given(customClient.post()).willReturn(WebClient.builder().build().post());
this.tokenResponseClient.setWebClient(customClient);
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(customClient).post();
}
Reusable Method for MCI (click to expand)
public class MockWebClient {
public static WebClient createMockWebClient() {
WebClient mockWebClient = mock();
given(mockWebClient.post()).willReturn(WebClient.builder().build().post());
return mockWebClient;
}
}
Mock Clone Instance #spring-security_MCI_85
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.client.userinfo.OAuth2UserService<org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest, org.springframework.security.oauth2.core.user.OAuth2User>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
@BeforeEach
public void setUp() {
userService = mock(OAuth2UserService.class);
}
userService
The refactoring details in each test cases
Test Case ID #spring-security_Test_85_1
Test Case Name: loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\userinfo\DelegatingOAuth2UserServiceTests.java)
Mock Object Variable Name: userService
Suggested Diff
@@
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
- OAuth2UserService<OAuth2UserRequest, OAuth2User> userService = mock(OAuth2UserService.class);
+ // removed local mock; replaced with global field `userService`
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService, userService));
assertThatIllegalArgumentException().isThrownBy(() -> delegatingUserService.loadUser(null));
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService, userService));
assertThatIllegalArgumentException().isThrownBy(() -> delegatingUserService.loadUser(null));
}
Reusable Method for MCI (click to expand)
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
@BeforeEach
public void setUp() {
userService = mock(OAuth2UserService.class);
}
userService
Test Case ID #spring-security_Test_85_2
Test Case Name: loadUserWhenUserServiceCanLoadThenReturnUser(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\userinfo\DelegatingOAuth2UserServiceTests.java)
Mock Object Variable Name: userService1
Suggested Diff
@@
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCanLoadThenReturnUser() {
- OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
+ // removed local mock; replaced with global field `userService`
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
OAuth2User mockUser = mock(OAuth2User.class);
given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser);
- DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
+ DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isEqualTo(mockUser);
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCanLoadThenReturnUser() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
OAuth2User mockUser = mock(OAuth2User.class);
given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isEqualTo(mockUser);
}
Reusable Method for MCI (click to expand)
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
@BeforeEach
public void setUp() {
userService = mock(OAuth2UserService.class);
}
userService
Test Case ID #spring-security_Test_85_3
Test Case Name: loadUserWhenUserServiceCannotLoadThenReturnNull(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\userinfo\DelegatingOAuth2UserServiceTests.java)
Mock Object Variable Name: userService1
Suggested Diff
@@
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCannotLoadThenReturnNull() {
- OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
+ // removed local mock; replaced with global field `userService`
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
- DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
+ DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isNull();
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCannotLoadThenReturnNull() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isNull();
}
Reusable Method for MCI (click to expand)
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
@BeforeEach
public void setUp() {
userService = mock(OAuth2UserService.class);
}
userService
Mock Clone Instance #spring-security_MCI_86
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.client.userinfo.OAuth2UserService<org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest, org.springframework.security.oauth2.core.user.OAuth2User>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3;
@BeforeEach
public void setUp() {
userService3 = mock(OAuth2UserService.class);
}
userService3
The refactoring details in each test cases
Test Case ID #spring-security_Test_86_1
Test Case Name: loadUserWhenUserServiceCanLoadThenReturnUser(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\userinfo\DelegatingOAuth2UserServiceTests.java)
Mock Object Variable Name: userService2
Suggested Diff
@@
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCanLoadThenReturnUser() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
- OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
+ // removed local mock; replaced with global field `userService3`
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
OAuth2User mockUser = mock(OAuth2User.class);
given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService3, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isEqualTo(mockUser);
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCanLoadThenReturnUser() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
OAuth2User mockUser = mock(OAuth2User.class);
given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isEqualTo(mockUser);
}
Reusable Method for MCI (click to expand)
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3;
@BeforeEach
public void setUp() {
userService3 = mock(OAuth2UserService.class);
}
userService3
Test Case ID #spring-security_Test_86_2
Test Case Name: loadUserWhenUserServiceCannotLoadThenReturnNull(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\userinfo\DelegatingOAuth2UserServiceTests.java)
Mock Object Variable Name: userService2
Suggested Diff
@@
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCannotLoadThenReturnNull() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
- OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
+ // removed local mock; replaced with global field `userService3`
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService3, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isNull();
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCannotLoadThenReturnNull() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isNull();
}
Reusable Method for MCI (click to expand)
private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3;
@BeforeEach
public void setUp() {
userService3 = mock(OAuth2UserService.class);
}
userService3
Mock Clone Instance #spring-security_MCI_87
- Scope: method level
- Mocked Class:
jakarta.servlet.Filter
- Test Case Count: 6
- MO Count: 6
Reusable Method
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
The refactoring details in each test cases
Test Case ID #spring-security_Test_87_1
Test Case Name: onStartupWhenInsertFiltersThenInserted(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter1
Suggested Diff
@@
+ // Cannot refactor mock `filter1`: ambiguous mapping for new variable name
Original Test Code (click to expand)
@Test
public void onStartupWhenInsertFiltersThenInserted() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context).addFilter(anyString(), eq(filter1));
verify(context).addFilter(anyString(), eq(filter2));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Test Case ID #spring-security_Test_87_2
Test Case Name: onStartupWhenDuplicateFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter1
Suggested Diff
@@
+ // Cannot refactor mock `filter1`: ambiguous new variable name 'filter1 filter2'
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterInsertedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Test Case ID #spring-security_Test_87_3
Test Case Name: onStartupWhenNullFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter
Suggested Diff
@@
+ // Cannot refactor mock `filter`: ambiguous mapping for new variable name
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterInsertedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Test Case ID #spring-security_Test_87_4
Test Case Name: onStartupWhenAppendFiltersThenAppended(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter1
Suggested Diff
@@
+ // Cannot refactor mock `filter1`: ambiguous new variable name 'filter1 filter2'
Original Test Code (click to expand)
@Test
public void onStartupWhenAppendFiltersThenAppended() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context, times(3)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Test Case ID #spring-security_Test_87_5
Test Case Name: onStartupWhenDuplicateFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter1
Suggested Diff
@@
+ // Cannot refactor mock `filter1`: ambiguous mapping for new variable name
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterAppendedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Test Case ID #spring-security_Test_87_6
Test Case Name: onStartupWhenNullFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: filter
Suggested Diff
@@
+ // Cannot refactor mock `filter`: ambiguous mapping for new variable name
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterAppendedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private Filter filter1; private Filter filter2;
@BeforeEach
public void setUp() {
filter1 = mock(Filter.class); filter2 = mock(Filter.class);
}
filter1; filter2;
Mock Clone Instance #spring-security_MCI_88
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static OAuth2AuthorizationRequestResolver createMockOAuth2AuthorizationRequestResolver(OAuth2AuthorizationRequest result) {
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
given(resolver.resolve(any())).willReturn(result);
return resolver;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_88_1
Test Case Name: doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: resolver
Suggested Diff
@@
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
- OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).build();
- given(resolver.resolve(any())).willReturn(result);
+ OAuth2AuthorizationRequestResolver resolver = createMockOAuth2AuthorizationRequestResolver(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "idp=https://other.provider.com");
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter("idp", "https://other.provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "idp=https://other.provider.com");
}
Reusable Method for MCI (click to expand)
private static OAuth2AuthorizationRequestResolver createMockOAuth2AuthorizationRequestResolver(OAuth2AuthorizationRequest result) {
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
given(resolver.resolve(any())).willReturn(result);
return resolver;
}
Test Case ID #spring-security_Test_88_2
Test Case Name: doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: resolver
Suggested Diff
@@
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
- OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest defaultAuthorizationRequest = defaultAuthorizationRequestResolver.resolve(request);
Map<String, Object> additionalParameters = new HashMap<>(defaultAuthorizationRequest.getAdditionalParameters());
additionalParameters.put(loginHintParamName, request.getParameter(loginHintParamName));
// @formatter:off
String customAuthorizationRequestUri = UriComponentsBuilder.fromUriString(defaultAuthorizationRequest.getAuthorizationRequestUri()).queryParam(loginHintParamName, additionalParameters.get(loginHintParamName)).build(true).toUriString();
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).authorizationRequestUri(customAuthorizationRequestUri).build();
// @formatter:on
- given(resolver.resolve(any())).willReturn(result);
+ OAuth2AuthorizationRequestResolver resolver = createMockOAuth2AuthorizationRequestResolver(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "login_hint=user@provider\\.com");
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
String loginHintParamName = "login_hint";
request.addParameter(loginHintParamName, "user@provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest defaultAuthorizationRequest = defaultAuthorizationRequestResolver.resolve(request);
Map<String, Object> additionalParameters = new HashMap<>(defaultAuthorizationRequest.getAdditionalParameters());
additionalParameters.put(loginHintParamName, request.getParameter(loginHintParamName));
String customAuthorizationRequestUri = UriComponentsBuilder.fromUriString(defaultAuthorizationRequest.getAuthorizationRequestUri()).queryParam(loginHintParamName, additionalParameters.get(loginHintParamName)).build(true).toUriString();
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).authorizationRequestUri(customAuthorizationRequestUri).build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "login_hint=user@provider\\.com");
}
Reusable Method for MCI (click to expand)
private static OAuth2AuthorizationRequestResolver createMockOAuth2AuthorizationRequestResolver(OAuth2AuthorizationRequest result) {
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
given(resolver.resolve(any())).willReturn(result);
return resolver;
}
Mock Clone Instance #spring-security_MCI_89
- Scope: method level
- Mocked Class:
org.springframework.security.core.userdetails.ReactiveUserDetailsService
- Test Case Count: 3
- MO Count: 3
Reusable Method
private ReactiveUserDetailsService userDetailsService;
@BeforeEach
public void setUp() {
userDetailsService = mock(ReactiveUserDetailsService.class);
}
userDetailsService;
The refactoring details in each test cases
Test Case ID #spring-security_Test_89_1
Test Case Name: constructorWhenOneTimeTokenServiceNullThenIllegalArgumentException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ott\reactive\OneTimeTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
@Test
public void constructorWhenOneTimeTokenServiceNullThenIllegalArgumentException() {
- ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
+ // removed local mock; replaced with global field `userDetailsService`
// @formatter:off
assertThatIllegalArgumentException().isThrownBy(() -> new OneTimeTokenReactiveAuthenticationManager(null, userDetailsService));
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void constructorWhenOneTimeTokenServiceNullThenIllegalArgumentException() {
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
assertThatIllegalArgumentException().isThrownBy(() -> new OneTimeTokenReactiveAuthenticationManager(null, userDetailsService));
}
Reusable Method for MCI (click to expand)
private ReactiveUserDetailsService userDetailsService;
@BeforeEach
public void setUp() {
userDetailsService = mock(ReactiveUserDetailsService.class);
}
userDetailsService;
Test Case ID #spring-security_Test_89_2
Test Case Name: authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ott\reactive\OneTimeTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
@Test
void authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
- ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
+ // removed local mock; replaced with global field `userDetailsService`
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
// @formatter:off
assertThatExceptionOfType(InvalidOneTimeTokenException.class).isThrownBy(() -> this.authenticationManager.authenticate(OneTimeTokenAuthenticationToken.unauthenticated(TOKEN)).block());
// @formatter:on
}
Original Test Code (click to expand)
@Test
void authenticateWhenInvalidOneTimeTokenAuthenticationTokenIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
assertThatExceptionOfType(InvalidOneTimeTokenException.class).isThrownBy(() -> this.authenticationManager.authenticate(OneTimeTokenAuthenticationToken.unauthenticated(TOKEN)).block());
}
Reusable Method for MCI (click to expand)
private ReactiveUserDetailsService userDetailsService;
@BeforeEach
public void setUp() {
userDetailsService = mock(ReactiveUserDetailsService.class);
}
userDetailsService;
Test Case ID #spring-security_Test_89_3
Test Case Name: authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ott\reactive\OneTimeTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: userDetailsService
Suggested Diff
@@
@Test
void authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
- ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
+ // removed local mock; replaced with global field `userDetailsService`
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
// @formatter:off
Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD)).block();
// @formatter:on
assertThat(authentication).isNull();
}
Original Test Code (click to expand)
@Test
void authenticateWhenIncorrectTypeOfAuthenticationIsPresentThenFail() {
ReactiveOneTimeTokenService oneTimeTokenService = mock(ReactiveOneTimeTokenService.class);
given(oneTimeTokenService.consume(ArgumentMatchers.any(OneTimeTokenAuthenticationToken.class))).willReturn(Mono.empty());
ReactiveUserDetailsService userDetailsService = mock(ReactiveUserDetailsService.class);
this.authenticationManager = new OneTimeTokenReactiveAuthenticationManager(oneTimeTokenService, userDetailsService);
Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD)).block();
assertThat(authentication).isNull();
}
Reusable Method for MCI (click to expand)
private ReactiveUserDetailsService userDetailsService;
@BeforeEach
public void setUp() {
userDetailsService = mock(ReactiveUserDetailsService.class);
}
userDetailsService;
Mock Clone Instance #spring-security_MCI_90
- Scope: class level
- Mocked Class:
org.aopalliance.intercept.MethodInvocation
- Test Case Count: 2
- MO Count: 3
Reusable Method
public class MockMethodInvocation {
public static MethodInvocation createMockMethodInvocation(Object proceedReturn) throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
given(mockMethodInvocation.proceed()).willReturn(proceedReturn);
return mockMethodInvocation;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_90_1
Test Case Name: beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterMethodInterceptorTests.java)
Mock Object Variable Name: mockMethodInvocation
Suggested Diff
@@
@Test
public void beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject() throws Throwable {
- MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
- given(mockMethodInvocation.proceed()).willReturn(result.getResult());
+ MethodInvocation mockMethodInvocation = MockMethodInvocation.createMockMethodInvocation(result.getResult());
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
Object returnedObject = advice.invoke(mockMethodInvocation);
assertThat(returnedObject).isEqualTo(result.getResult());
verify(mockAuthorizationManager).check(any(Supplier.class), any(MethodInvocationResult.class));
}
@@
Original Test Code (click to expand)
@Test
public void beforeWhenMockAuthorizationManagerThenCheckAndReturnedObject() throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
given(mockMethodInvocation.proceed()).willReturn(result.getResult());
AuthorizationManager<MethodInvocationResult> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
Object returnedObject = advice.invoke(mockMethodInvocation);
assertThat(returnedObject).isEqualTo(result.getResult());
verify(mockAuthorizationManager).check(any(Supplier.class), any(MethodInvocationResult.class));
}
Reusable Method for MCI (click to expand)
public class MockMethodInvocation {
public static MethodInvocation createMockMethodInvocation(Object proceedReturn) throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
given(mockMethodInvocation.proceed()).willReturn(proceedReturn);
return mockMethodInvocation;
}
}
Test Case ID #spring-security_Test_90_2
Test Case Name: invokeWhenAuthorizationEventPublisherThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterMethodInterceptorTests.java)
Mock Object Variable Name: mockMethodInvocation
Suggested Diff
@@
SecurityContextHolder.setContext(securityContext);
- MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
- MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
- given(mockMethodInvocation.proceed()).willReturn(result.getResult());
+ MethodInvocationResult result = new MethodInvocationResult(null, new Object());
+ MethodInvocation mockMethodInvocation = MockMethodInvocation.createMockMethodInvocation(result.getResult());
advice.invoke(mockMethodInvocation);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(MethodInvocationResult.class), any(AuthorizationDecision.class));
Original Test Code (click to expand)
@Test
public void invokeWhenAuthorizationEventPublisherThenUses() throws Throwable {
AuthorizationManagerAfterMethodInterceptor advice = new AuthorizationManagerAfterMethodInterceptor(Pointcut.TRUE, AuthenticatedAuthorizationManager.authenticated());
AuthorizationEventPublisher eventPublisher = mock(AuthorizationEventPublisher.class);
doCallRealMethod().when(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(), any(AuthorizationResult.class));
advice.setAuthorizationEventPublisher(eventPublisher);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
SecurityContextHolder.setContext(securityContext);
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
given(mockMethodInvocation.proceed()).willReturn(result.getResult());
advice.invoke(mockMethodInvocation);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(MethodInvocationResult.class), any(AuthorizationDecision.class));
}
Reusable Method for MCI (click to expand)
public class MockMethodInvocation {
public static MethodInvocation createMockMethodInvocation(Object proceedReturn) throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
given(mockMethodInvocation.proceed()).willReturn(proceedReturn);
return mockMethodInvocation;
}
}
Test Case ID #spring-security_Test_90_3
Test Case Name: invokeWhenAuthorizationEventPublisherThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: mockMethodInvocation
Suggested Diff
@@
SecurityContextHolder.setContext(securityContext);
- MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
- MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
- given(mockMethodInvocation.proceed()).willReturn(result.getResult());
+ MethodInvocationResult result = new MethodInvocationResult(null, new Object());
+ MethodInvocation mockMethodInvocation = MockMethodInvocation.createMockMethodInvocation(result.getResult());
advice.invoke(mockMethodInvocation);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(MethodInvocation.class), any(AuthorizationDecision.class));
@@
Original Test Code (click to expand)
@Test
public void invokeWhenAuthorizationEventPublisherThenUses() throws Throwable {
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, AuthenticatedAuthorizationManager.authenticated());
AuthorizationEventPublisher eventPublisher = mock(AuthorizationEventPublisher.class);
doCallRealMethod().when(eventPublisher).publishAuthorizationEvent(any(), any(), any(AuthorizationResult.class));
advice.setAuthorizationEventPublisher(eventPublisher);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
SecurityContextHolder.setContext(securityContext);
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
MethodInvocationResult result = new MethodInvocationResult(mockMethodInvocation, new Object());
given(mockMethodInvocation.proceed()).willReturn(result.getResult());
advice.invoke(mockMethodInvocation);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(MethodInvocation.class), any(AuthorizationDecision.class));
}
Reusable Method for MCI (click to expand)
public class MockMethodInvocation {
public static MethodInvocation createMockMethodInvocation(Object proceedReturn) throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
given(mockMethodInvocation.proceed()).willReturn(proceedReturn);
return mockMethodInvocation;
}
}
Mock Clone Instance #spring-security_MCI_91
- Scope: method level
- Mocked Class:
org.aopalliance.intercept.MethodInvocation
- Test Case Count: 3
- MO Count: 3
Reusable Method
private MethodInvocation mockMethodInvocation;
@BeforeEach
public void setUp() {
mockMethodInvocation = mock(MethodInvocation.class);
}
mockMethodInvocation;
The refactoring details in each test cases
Test Case ID #spring-security_Test_91_1
Test Case Name: beforeWhenMockAuthorizationManagerThenCheck(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: mockMethodInvocation
Suggested Diff
@@
@Test
public void beforeWhenMockAuthorizationManagerThenCheck() throws Throwable {
- MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
+ // removed local mock; replaced with global field `mockMethodInvocation`
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
advice.invoke(mockMethodInvocation);
verify(mockAuthorizationManager).check(any(Supplier.class), eq(mockMethodInvocation));
}
Original Test Code (click to expand)
@Test
public void beforeWhenMockAuthorizationManagerThenCheck() throws Throwable {
MethodInvocation mockMethodInvocation = mock(MethodInvocation.class);
AuthorizationManager<MethodInvocation> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, mockAuthorizationManager);
advice.invoke(mockMethodInvocation);
verify(mockAuthorizationManager).check(any(Supplier.class), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private MethodInvocation mockMethodInvocation;
@BeforeEach
public void setUp() {
mockMethodInvocation = mock(MethodInvocation.class);
}
mockMethodInvocation;
Test Case ID #spring-security_Test_91_2
Test Case Name: beforeWhenMockSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: invocation
Suggested Diff
@@
@Test
public void beforeWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
Authentication authentication = new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("authority"));
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(new SecurityContextImpl(authentication));
- MethodInvocation invocation = mock(MethodInvocation.class);
+ // removed local mock; replaced with global field `mockMethodInvocation`
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, authorizationManager);
advice.setSecurityContextHolderStrategy(strategy);
- advice.invoke(invocation);
+ advice.invoke(mockMethodInvocation);
verify(strategy).getContext();
}
Original Test Code (click to expand)
@Test
public void beforeWhenMockSecurityContextHolderStrategyThenUses() throws Throwable {
Authentication authentication = new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("authority"));
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(new SecurityContextImpl(authentication));
MethodInvocation invocation = mock(MethodInvocation.class);
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, authorizationManager);
advice.setSecurityContextHolderStrategy(strategy);
advice.invoke(invocation);
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
private MethodInvocation mockMethodInvocation;
@BeforeEach
public void setUp() {
mockMethodInvocation = mock(MethodInvocation.class);
}
mockMethodInvocation;
Test Case ID #spring-security_Test_91_3
Test Case Name: beforeWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeMethodInterceptorTests.java)
Mock Object Variable Name: invocation
Suggested Diff
@@
@Test
public void beforeWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
Authentication authentication = new TestingAuthenticationToken("john", "password", AuthorityUtils.createAuthorityList("authority"));
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(new SecurityContextImpl(authentication));
- MethodInvocation invocation = mock(MethodInvocation.class);
+ // removed local mock; replaced with global field `mockMethodInvocation`
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, authorizationManager);
SecurityContextHolderStrategy saved = SecurityContextHolder.getContextHolderStrategy();
SecurityContextHolder.setContextHolderStrategy(strategy);
- advice.invoke(invocation);
+ advice.invoke(mockMethodInvocation);
verify(strategy).getContext();
SecurityContextHolder.setContextHolderStrategy(saved);
}
Original Test Code (click to expand)
@Test
public void beforeWhenStaticSecurityContextHolderStrategyAfterConstructorThenUses() throws Throwable {
Authentication authentication = new TestingAuthenticationToken("john", "password", AuthorityUtils.createAuthorityList("authority"));
SecurityContextHolderStrategy strategy = mockSecurityContextHolderStrategy(new SecurityContextImpl(authentication));
MethodInvocation invocation = mock(MethodInvocation.class);
AuthorizationManager<MethodInvocation> authorizationManager = AuthenticatedAuthorizationManager.authenticated();
AuthorizationManagerBeforeMethodInterceptor advice = new AuthorizationManagerBeforeMethodInterceptor(Pointcut.TRUE, authorizationManager);
SecurityContextHolderStrategy saved = SecurityContextHolder.getContextHolderStrategy();
SecurityContextHolder.setContextHolderStrategy(strategy);
advice.invoke(invocation);
verify(strategy).getContext();
SecurityContextHolder.setContextHolderStrategy(saved);
}
Reusable Method for MCI (click to expand)
private MethodInvocation mockMethodInvocation;
@BeforeEach
public void setUp() {
mockMethodInvocation = mock(MethodInvocation.class);
}
mockMethodInvocation;
Mock Clone Instance #spring-security_MCI_92
- Scope: class level
- Mocked Class:
org.springframework.security.messaging.util.matcher.MessageMatcher<java.lang.Object>
- Test Case Count: 10
- MO Count: 13
Reusable Method
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_92_1
Test Case Name: matchesSingleTrue(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleTrue() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_2
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
given(this.delegate2.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_3
Test Case Name: matchesSingleFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleFalse() {
- given(this.delegate.matches(this.message)).willReturn(false);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, false);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_4
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
- given(this.delegate.matches(this.message)).willReturn(false);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_5
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_6
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
- given(this.delegate2.matches(this.message)).willReturn(true);
+ this.delegate2 = MockMessageMatcher.createMockMessageMatcher(this.message, true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(true);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_7
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\AndMessageMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
- given(this.delegate2.matches(this.message)).willReturn(false);
+ this.delegate2 = MockMessageMatcher.createMockMessageMatcher(this.message, false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new AndMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_8
Test Case Name: matchesSingleTrue(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleTrue() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_9
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_10
Test Case Name: matchesSingleFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleFalse() {
- given(this.delegate.matches(this.message)).willReturn(false);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, false);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_11
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
- given(this.delegate.matches(this.message)).willReturn(false);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_12
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
- given(this.delegate.matches(this.message)).willReturn(true);
+ this.delegate = MockMessageMatcher.createMockMessageMatcher(this.message, true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.message)).willReturn(true);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_92_13
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\messaging\src\test\java\org\springframework\security\messaging\util\matcher\OrMessageMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
- given(this.delegate2.matches(this.message)).willReturn(false);
+ this.delegate2 = MockMessageMatcher.createMockMessageMatcher(this.message, false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.message)).willReturn(false);
given(this.delegate2.matches(this.message)).willReturn(false);
this.matcher = new OrMessageMatcher<>(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.message)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockMessageMatcher {
public static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> mock = mock(MessageMatcher.class);
given(mock.matches(message)).willReturn(matchesReturn);
return mock;
}
}
Mock Clone Instance #spring-security_MCI_93
- Scope: method level
- Mocked Class:
org.springframework.security.messaging.util.matcher.MessageMatcher<java.lang.Object>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> matcher = mock(MessageMatcher.class);
given(matcher.matches(message)).willReturn(matchesReturn);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_93_1
Mock Object Variable Name: matcher1
Suggested Diff
@@
@BeforeEach
public void setup() {
this.expression1 = "permitAll";
this.expression2 = "denyAll";
this.matcherToExpression = new LinkedHashMap<>();
- this.matcherToExpression.put(this.matcher1, this.expression1);
this.matcherToExpression.put(this.matcher2, this.expression2);
this.source = ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource(this.matcherToExpression);
this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message);
}
@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
- given(this.matcher1.matches(this.message)).willReturn(true);
+ this.matcher1 = createMockMessageMatcher(this.message, true);
+ this.matcherToExpression.put(this.matcher1, this.expression1);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject)).isEqualTo(true);
}
Original Test Code (click to expand)
@BeforeEach
public void setup() {
this.expression1 = "permitAll";
this.expression2 = "denyAll";
this.matcherToExpression = new LinkedHashMap<>();
this.matcherToExpression.put(this.matcher1, this.expression1);
this.matcherToExpression.put(this.matcher2, this.expression2);
this.source = ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource(this.matcherToExpression);
this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message);
}
@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
given(this.matcher1.matches(this.message)).willReturn(true);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject)).isEqualTo(true);
}
Reusable Method for MCI (click to expand)
private static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> matcher = mock(MessageMatcher.class);
given(matcher.matches(message)).willReturn(matchesReturn);
return matcher;
}
Test Case ID #spring-security_Test_93_2
Mock Object Variable Name: matcher2
Suggested Diff
@@
@BeforeEach
public void setup() {
this.expression1 = "permitAll";
this.expression2 = "denyAll";
this.matcherToExpression = new LinkedHashMap<>();
this.matcherToExpression.put(this.matcher1, this.expression1);
- this.matcherToExpression.put(this.matcher2, this.expression2);
+ this.matcherToExpression.put(this.matcher2, this.expression2); // matcher2 will be replaced in test
this.source = ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource(this.matcherToExpression);
this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message);
}
@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
- given(this.matcher2.matches(this.message)).willReturn(true);
+ this.matcher2 = createMockMessageMatcher(this.message, true);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject)).isEqualTo(false);
}
Original Test Code (click to expand)
@BeforeEach
public void setup() {
this.expression1 = "permitAll";
this.expression2 = "denyAll";
this.matcherToExpression = new LinkedHashMap<>();
this.matcherToExpression.put(this.matcher1, this.expression1);
this.matcherToExpression.put(this.matcher2, this.expression2);
this.source = ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource(this.matcherToExpression);
this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message);
}
@Test
public void createExpressionMessageMetadataSourceMatchSecond() {
given(this.matcher2.matches(this.message)).willReturn(true);
Collection<ConfigAttribute> attrs = this.source.getAttributes(this.message);
assertThat(attrs).hasSize(1);
ConfigAttribute attr = attrs.iterator().next();
assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
assertThat(((MessageExpressionConfigAttribute) attr).getAuthorizeExpression().getValue(this.rootObject)).isEqualTo(false);
}
Reusable Method for MCI (click to expand)
private static MessageMatcher<Object> createMockMessageMatcher(Message<Object> message, boolean matchesReturn) {
MessageMatcher<Object> matcher = mock(MessageMatcher.class);
given(matcher.matches(message)).willReturn(matchesReturn);
return matcher;
}
Mock Clone Instance #spring-security_MCI_94
- Scope: class level
- Mocked Class:
org.springframework.security.authentication.ReactiveAuthenticationManager
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Authentication authentication, Mono<?> monoReturn) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(authentication)).willReturn(monoReturn);
return authenticationManager;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_94_1
Test Case Name: resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerReactiveAuthenticationManagerResolverDeprecatedTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
Authentication token = withBearerToken(this.jwt);
- ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
- given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
+ ReactiveAuthenticationManager authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager(token, Mono.empty());
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.just(authenticationManager));
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(any());
@@
Original Test Code (click to expand)
@Test
public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() {
Authentication token = withBearerToken(this.jwt);
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.just(authenticationManager));
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(any());
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Authentication authentication, Mono<?> monoReturn) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(authentication)).willReturn(monoReturn);
return authenticationManager;
}
}
Test Case ID #spring-security_Test_94_2
Test Case Name: resolveWhenUsingExternalSourceThenRespondsToChanges(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerReactiveAuthenticationManagerResolverDeprecatedTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
- ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
- given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
+ ReactiveAuthenticationManager authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager(token, Mono.empty());
authenticationManagers.put("trusted", authenticationManager);
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(token);
authenticationManagers.clear();
Original Test Code (click to expand)
@Test
public void resolveWhenUsingExternalSourceThenRespondsToChanges() {
Authentication token = withBearerToken(this.jwt);
Map<String, ReactiveAuthenticationManager> authenticationManagers = new HashMap<>();
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer)));
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
authenticationManagers.put("trusted", authenticationManager);
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(token);
authenticationManagers.clear();
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Authentication authentication, Mono<?> monoReturn) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(authentication)).willReturn(monoReturn);
return authenticationManager;
}
}
Test Case ID #spring-security_Test_94_3
Test Case Name: resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerReactiveAuthenticationManagerResolverTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
Authentication token = withBearerToken(this.jwt);
- ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
- given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
+ ReactiveAuthenticationManager authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager(token, Mono.empty());
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.just(authenticationManager));
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(any());
@@
Original Test Code (click to expand)
@Test
public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() {
Authentication token = withBearerToken(this.jwt);
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.just(authenticationManager));
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(any());
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Authentication authentication, Mono<?> monoReturn) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(authentication)).willReturn(monoReturn);
return authenticationManager;
}
}
Test Case ID #spring-security_Test_94_4
Test Case Name: resolveWhenUsingExternalSourceThenRespondsToChanges(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\JwtIssuerReactiveAuthenticationManagerResolverTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
- ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
- given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
+ ReactiveAuthenticationManager authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager(token, Mono.empty());
authenticationManagers.put("trusted", authenticationManager);
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(token);
@@
Original Test Code (click to expand)
@Test
public void resolveWhenUsingExternalSourceThenRespondsToChanges() {
Authentication token = withBearerToken(this.jwt);
Map<String, ReactiveAuthenticationManager> authenticationManagers = new HashMap<>();
JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver((issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer)));
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(token)).willReturn(Mono.empty());
authenticationManagers.put("trusted", authenticationManager);
authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block();
verify(authenticationManager).authenticate(token);
authenticationManagers.clear();
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block()).withMessageContaining("Invalid issuer");
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Authentication authentication, Mono<?> monoReturn) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(authentication)).willReturn(monoReturn);
return authenticationManager;
}
}
Mock Clone Instance #spring-security_MCI_95
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.ReactiveAuthenticationManager
- Test Case Count: 5
- MO Count: 6
Reusable Method
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_95_1
Test Case Name: authenticateWhenEmptyAndNotThenReturnsNotEmpty(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
- given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.empty());
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Test Case ID #spring-security_Test_95_2
Test Case Name: authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
- given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Original Test Code (click to expand)
@Test
public void authenticateWhenBadCredentialsThenDelegate2NotInvokedAndError() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Test Case ID #spring-security_Test_95_3
Test Case Name: authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond() {
- given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Test Case ID #spring-security_Test_95_4
Test Case Name: authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError() {
- given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Original Test Code (click to expand)
@Test
public void authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Test Case ID #spring-security_Test_95_5
Test Case Name: whenAccountStatusExceptionThenAuthenticationRequestIsIncluded(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
void whenAccountStatusExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new LockedException("");
- given(this.delegate1.authenticate(any())).willReturn(Mono.error(expected));
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.error(expected));
ReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1);
StepVerifier.create(manager.authenticate(this.authentication)).expectError(LockedException.class).verify();
assertThat(expected.getAuthenticationRequest()).isEqualTo(this.authentication);
}
@@
Original Test Code (click to expand)
@Test
void whenAccountStatusExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new LockedException("");
given(this.delegate1.authenticate(any())).willReturn(Mono.error(expected));
ReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1);
StepVerifier.create(manager.authenticate(this.authentication)).expectError(LockedException.class).verify();
assertThat(expected.getAuthenticationRequest()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Test Case ID #spring-security_Test_95_6
Test Case Name: authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
- given(this.delegate2.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
+ this.delegate2 = createMockReactiveAuthenticationManager(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Original Test Code (click to expand)
@Test
public void authenticateWhenContinueOnErrorAndBothDelegatesBadCredentialsThenError() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
StepVerifier.create(manager.authenticate(this.authentication)).expectError(BadCredentialsException.class).verify();
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<?> authenticateReturn) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticateReturn);
return mock;
}
Mock Clone Instance #spring-security_MCI_96
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.ReactiveAuthenticationManager
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<Authentication> authenticationMono) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticationMono);
return mock;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_96_1
Test Case Name: authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed() {
- // delay to try and force delegate2 to finish (i.e. make sure we didn't use
- // flatMap)
- given(this.delegate1.authenticate(any())).willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
+ // delay to try and force delegate2 to finish (i.e. make sure we didn't use
+ // flatMap)
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication)).expectNext(this.authentication).verifyComplete();
}
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenNotEmptyThenOtherDelegatesNotSubscribed() {
given(this.delegate1.authenticate(any())).willReturn(Mono.just(this.authentication).delayElement(Duration.ofMillis(100)));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
StepVerifier.create(manager.authenticate(this.authentication)).expectNext(this.authentication).verifyComplete();
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<Authentication> authenticationMono) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticationMono);
return mock;
}
Test Case ID #spring-security_Test_96_2
Test Case Name: authenticateWhenContinueOnErrorAndDelegate1NotEmptyThenReturnsNotEmpty(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
@Test
public void authenticateWhenContinueOnErrorAndDelegate1NotEmptyThenReturnsNotEmpty() {
- given(this.delegate1.authenticate(any())).willReturn(Mono.just(this.authentication));
+ this.delegate1 = createMockReactiveAuthenticationManager(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenContinueOnErrorAndDelegate1NotEmptyThenReturnsNotEmpty() {
given(this.delegate1.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<Authentication> authenticationMono) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticationMono);
return mock;
}
Test Case ID #spring-security_Test_96_3
Test Case Name: authenticateWhenEmptyAndNotThenReturnsNotEmpty(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
- given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
+ this.delegate2 = createMockReactiveAuthenticationManager(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenEmptyAndNotThenReturnsNotEmpty() {
given(this.delegate1.authenticate(any())).willReturn(Mono.empty());
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = new DelegatingReactiveAuthenticationManager(this.delegate1, this.delegate2);
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<Authentication> authenticationMono) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticationMono);
return mock;
}
Test Case ID #spring-security_Test_96_4
Test Case Name: authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\DelegatingReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
- given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
+ this.delegate2 = createMockReactiveAuthenticationManager(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenContinueOnErrorAndFirstBadCredentialsThenTriesSecond() {
given(this.delegate1.authenticate(any())).willReturn(Mono.error(new BadCredentialsException("Test")));
given(this.delegate2.authenticate(any())).willReturn(Mono.just(this.authentication));
DelegatingReactiveAuthenticationManager manager = managerWithContinueOnError();
assertThat(manager.authenticate(this.authentication).block()).isEqualTo(this.authentication);
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(Mono<Authentication> authenticationMono) {
ReactiveAuthenticationManager mock = mock(ReactiveAuthenticationManager.class);
given(mock.authenticate(any())).willReturn(authenticationMono);
return mock;
}
Mock Clone Instance #spring-security_MCI_97
- Scope: class level
- Mocked Class:
org.springframework.security.authentication.ReactiveAuthenticationManager
- Test Case Count: 6
- MO Count: 6
Reusable Method
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_97_1
Mock Object Variable Name: customAuthenticationManager
Suggested Diff
@@
ReactiveAuthenticationManager defaultAuthenticationManager = mock(ReactiveAuthenticationManager.class);
- ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
given(defaultAuthenticationManager.authenticate(any())).willThrow(new RuntimeException("should not interact with default auth manager"));
- given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("user", "password", "ROLE_USER", "ROLE_ADMIN")));
+ ReactiveAuthenticationManager customAuthenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("user", "password", "ROLE_USER", "ROLE_ADMIN");
// @formatter:off
SecurityWebFilterChain securityWebFilter = this.http.authenticationManager(defaultAuthenticationManager).formLogin().authenticationManager(customAuthenticationManager).and().build();
@@
Original Test Code (click to expand)
@Test
public void customAuthenticationManager() {
ReactiveAuthenticationManager defaultAuthenticationManager = mock(ReactiveAuthenticationManager.class);
ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
given(defaultAuthenticationManager.authenticate(any())).willThrow(new RuntimeException("should not interact with default auth manager"));
given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("user", "password", "ROLE_USER", "ROLE_ADMIN")));
SecurityWebFilterChain securityWebFilter = this.http.authenticationManager(defaultAuthenticationManager).formLogin().authenticationManager(customAuthenticationManager).and().build();
WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();
DefaultLoginPage loginPage = DefaultLoginPage.to(driver).assertAt();
HomePage homePage = loginPage.loginForm().username("user").password("password").submit(HomePage.class);
homePage.assertAt();
verifyNoMoreInteractions(defaultAuthenticationManager);
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Test Case ID #spring-security_Test_97_2
Test Case Name: basicWithCustomAuthenticationManager(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: customAuthenticationManager
Suggested Diff
@@
public void basicWithCustomAuthenticationManager() {
- ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
- given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
+ ReactiveAuthenticationManager customAuthenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("rob", "rob", "ROLE_USER", "ROLE_ADMIN");
// @formatter:off
SecurityWebFilterChain securityFilterChain = this.http.httpBasic().authenticationManager(customAuthenticationManager).and().build();
// @formatter:on
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
// @formatter:off
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
// @formatter:on
verifyNoMoreInteractions(this.authenticationManager);
}
Original Test Code (click to expand)
@Test
public void basicWithCustomAuthenticationManager() {
ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
SecurityWebFilterChain securityFilterChain = this.http.httpBasic().authenticationManager(customAuthenticationManager).and().build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
verifyNoMoreInteractions(this.authenticationManager);
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Test Case ID #spring-security_Test_97_3
Test Case Name: requestWhenBasicWithAuthenticationManagerInLambdaThenAuthenticationManagerUsed(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: customAuthenticationManager
Suggested Diff
@@
@Test
public void requestWhenBasicWithAuthenticationManagerInLambdaThenAuthenticationManagerUsed() {
- ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
- given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
+ ReactiveAuthenticationManager customAuthenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("rob", "rob", "ROLE_USER", "ROLE_ADMIN");
// @formatter:off
SecurityWebFilterChain securityFilterChain = this.http.httpBasic((httpBasic) -> httpBasic.authenticationManager(customAuthenticationManager)).build();
// @formatter:on
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
// @formatter:off
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
// @formatter:on
verifyNoMoreInteractions(this.authenticationManager);
verify(customAuthenticationManager).authenticate(any(Authentication.class));
}
@@
Original Test Code (click to expand)
@Test
public void requestWhenBasicWithAuthenticationManagerInLambdaThenAuthenticationManagerUsed() {
ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
SecurityWebFilterChain securityFilterChain = this.http.httpBasic((httpBasic) -> httpBasic.authenticationManager(customAuthenticationManager)).build();
WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
verifyNoMoreInteractions(this.authenticationManager);
verify(customAuthenticationManager).authenticate(any(Authentication.class));
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Test Case ID #spring-security_Test_97_4
Test Case Name: basic(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
@Test
public void basic() {
- given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
+ this.authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("rob", "rob", "ROLE_USER", "ROLE_ADMIN");
this.http.httpBasic();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().authenticated();
WebTestClient client = buildClient();
// @formatter:off
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
// @formatter:on
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
Original Test Code (click to expand)
@Test
public void basic() {
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.httpBasic();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().authenticated();
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Test Case ID #spring-security_Test_97_5
Test Case Name: basicWithGlobalWebSessionServerSecurityContextRepository(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
@Test
public void basicWithGlobalWebSessionServerSecurityContextRepository() {
- given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
+ this.authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("rob", "rob", "ROLE_USER", "ROLE_ADMIN");
this.http.securityContextRepository(new WebSessionServerSecurityContextRepository());
this.http.httpBasic();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().authenticated();
WebTestClient client = buildClient();
// @formatter:off
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
// @formatter:on
assertThat(result.getResponseCookies().getFirst("SESSION")).isNotNull();
}
@@
Original Test Code (click to expand)
@Test
public void basicWithGlobalWebSessionServerSecurityContextRepository() {
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.securityContextRepository(new WebSessionServerSecurityContextRepository());
this.http.httpBasic();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().authenticated();
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Test Case ID #spring-security_Test_97_6
Test Case Name: basicWithAnonymous(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: authenticationManager
Suggested Diff
@@
@Test
public void basicWithAnonymous() {
- given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
+ this.authenticationManager = MockReactiveAuthenticationManager.createMockReactiveAuthenticationManager("rob", "rob", "ROLE_USER", "ROLE_ADMIN");
this.http.httpBasic().and().anonymous();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().hasAuthority("ROLE_ADMIN");
WebTestClient client = buildClient();
// @formatter:off
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
// @formatter:on
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
Original Test Code (click to expand)
@Test
public void basicWithAnonymous() {
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
this.http.httpBasic().and().anonymous();
this.http.authenticationManager(this.authenticationManager);
ServerHttpSecurity.AuthorizeExchangeSpec authorize = this.http.authorizeExchange();
authorize.anyExchange().hasAuthority("ROLE_ADMIN");
WebTestClient client = buildClient();
EntityExchangeResult<String> result = client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectHeader().valueMatches(HttpHeaders.CACHE_CONTROL, ".+").expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok")).returnResult();
assertThat(result.getResponseCookies().getFirst("SESSION")).isNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveAuthenticationManager {
public static ReactiveAuthenticationManager createMockReactiveAuthenticationManager(String principal, String credentials, String... authorities) {
ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class);
given(authenticationManager.authenticate(any()))
.willReturn(Mono.just(new TestingAuthenticationToken(principal, credentials, authorities)));
return authenticationManager;
}
}
Mock Clone Instance #spring-security_MCI_98
- Scope: method level
- Mocked Class:
org.springframework.security.core.session.SessionDestroyedEvent
- Test Case Count: 5
- MO Count: 5
Reusable Method
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_98_1
Test Case Name: logout(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: event
Suggested Diff
@@
@Test
public void logout() throws Exception {
- SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
- given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
+ SessionDestroyedEvent event = createMockSessionDestroyedEvent(securityContext);
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
}
@@
Original Test Code (click to expand)
@Test
public void logout() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
Test Case ID #spring-security_Test_98_2
Test Case Name: logoutNullAuthentication(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: event
Suggested Diff
@@
public void logoutNullAuthentication() {
- SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
- given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
+ SessionDestroyedEvent event = createMockSessionDestroyedEvent(securityContext);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verifyNoMoreInteractions(event, securityContext);
}
Original Test Code (click to expand)
@Test
public void logoutNullAuthentication() {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verifyNoMoreInteractions(event, securityContext);
}
Reusable Method for MCI (click to expand)
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
Test Case ID #spring-security_Test_98_3
Test Case Name: logoutNonJaasAuthentication(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: event
Suggested Diff
@@
public void logoutNonJaasAuthentication() {
- SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
- given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
+ SessionDestroyedEvent event = createMockSessionDestroyedEvent(securityContext);
given(securityContext.getAuthentication()).willReturn(this.token);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verifyNoMoreInteractions(event, securityContext);
@@
Original Test Code (click to expand)
@Test
public void logoutNonJaasAuthentication() {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(this.token);
this.provider.handleLogout(event);
verify(event).getSecurityContexts();
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verifyNoMoreInteractions(event, securityContext);
}
Reusable Method for MCI (click to expand)
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
Test Case ID #spring-security_Test_98_4
Test Case Name: logoutNullLoginContext(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: event
Suggested Diff
@@
@Test
public void logoutNullLoginContext() {
- SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
- given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
+ SessionDestroyedEvent event = createMockSessionDestroyedEvent(securityContext);
given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verifyNoMoreInteractions(event, securityContext, token);
}
@@
Original Test Code (click to expand)
@Test
public void logoutNullLoginContext() {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verifyNoMoreInteractions(event, securityContext, token);
}
Reusable Method for MCI (click to expand)
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
Test Case ID #spring-security_Test_98_5
Test Case Name: logoutLoginException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: event
Suggested Diff
@@
public void logoutLoginException() throws Exception {
- SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
+ SessionDestroyedEvent event = createMockSessionDestroyedEvent(securityContext);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
- given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
@@
Original Test Code (click to expand)
@Test
public void logoutLoginException() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static SessionDestroyedEvent createMockSessionDestroyedEvent(SecurityContext securityContext) {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
return event;
}
Mock Clone Instance #spring-security_MCI_99
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.jwt.ReactiveJwtDecoder
- Test Case Count: 3
- MO Count: 3
Reusable Method
private ReactiveJwtDecoder beanWiredJwtDecoder;
@BeforeEach
public void setUp() {
beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
}
beanWiredJwtDecoder
The refactoring details in each test cases
Test Case ID #spring-security_Test_99_1
Test Case Name: getJwtDecoderWhenBeanWiredAndDslWiredThenDslTakesPrecedence(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\OAuth2ResourceServerSpecTests.java)
Mock Object Variable Name: beanWiredJwtDecoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenBeanWiredAndDslWiredThenDslTakesPrecedence() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
- ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
+ // removed local mock; replaced with global field `beanWiredJwtDecoder`
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean(ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenBeanWiredAndDslWiredThenDslTakesPrecedence() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean(ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}
Reusable Method for MCI (click to expand)
private ReactiveJwtDecoder beanWiredJwtDecoder;
@BeforeEach
public void setUp() {
beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
}
beanWiredJwtDecoder
Test Case ID #spring-security_Test_99_2
Test Case Name: getJwtDecoderWhenTwoBeansWiredAndDslWiredThenDslTakesPrecedence(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\OAuth2ResourceServerSpecTests.java)
Mock Object Variable Name: beanWiredJwtDecoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenTwoBeansWiredAndDslWiredThenDslTakesPrecedence() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
- ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
+ // removed local mock; replaced with global field `beanWiredJwtDecoder`
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
- context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
+ context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
- context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
+ context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenTwoBeansWiredAndDslWiredThenDslTakesPrecedence() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
ReactiveJwtDecoder dslWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
jwt.jwtDecoder(dslWiredJwtDecoder);
assertThat(jwt.getJwtDecoder()).isEqualTo(dslWiredJwtDecoder);
}
Reusable Method for MCI (click to expand)
private ReactiveJwtDecoder beanWiredJwtDecoder;
@BeforeEach
public void setUp() {
beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
}
beanWiredJwtDecoder
Test Case ID #spring-security_Test_99_3
Test Case Name: getJwtDecoderWhenTwoBeansWiredThenThrowsWiringException(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\OAuth2ResourceServerSpecTests.java)
Mock Object Variable Name: beanWiredJwtDecoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenTwoBeansWiredThenThrowsWiringException() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
- ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
+ // removed local mock; replaced with global field `beanWiredJwtDecoder`
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenTwoBeansWiredThenThrowsWiringException() {
GenericWebApplicationContext context = autowireWebServerGenericWebApplicationContext();
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ReactiveJwtDecoder beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
}
Reusable Method for MCI (click to expand)
private ReactiveJwtDecoder beanWiredJwtDecoder;
@BeforeEach
public void setUp() {
beanWiredJwtDecoder = mock(ReactiveJwtDecoder.class);
}
beanWiredJwtDecoder
Mock Clone Instance #spring-security_MCI_100
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.jwt.ReactiveJwtDecoder
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static ReactiveJwtDecoder createMockReactiveJwtDecoder(String token, Mono<?> monoReturn) {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode(token)).willReturn(monoReturn);
return jwtDecoder;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_100_1
Test Case Name: decodeWhenUninitializedThenSupplierInitializes(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
- ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
- given(jwtDecoder.decode("token")).willReturn(Mono.empty());
+ ReactiveJwtDecoder jwtDecoder = createMockReactiveJwtDecoder("token", Mono.empty());
SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(() -> jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
@@
Original Test Code (click to expand)
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(() -> jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private static ReactiveJwtDecoder createMockReactiveJwtDecoder(String token, Mono<?> monoReturn) {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode(token)).willReturn(monoReturn);
return jwtDecoder;
}
Test Case ID #spring-security_Test_100_2
Test Case Name: decodeWhenInitializedThenCaches(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
@Test
public void decodeWhenInitializedThenCaches() {
- ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
+ ReactiveJwtDecoder jwtDecoder = createMockReactiveJwtDecoder("token", Mono.empty());
Supplier<ReactiveJwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
- given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(supplier);
supplierReactiveJwtDecoder.decode("token").block();
supplierReactiveJwtDecoder.decode("token").block();
verify(supplier, times(1)).get();
verify(jwtDecoder, times(2)).decode("token");
}
@@
Original Test Code (click to expand)
@Test
public void decodeWhenInitializedThenCaches() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
Supplier<ReactiveJwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(supplier);
supplierReactiveJwtDecoder.decode("token").block();
supplierReactiveJwtDecoder.decode("token").block();
verify(supplier, times(1)).get();
verify(jwtDecoder, times(2)).decode("token");
}
Reusable Method for MCI (click to expand)
private static ReactiveJwtDecoder createMockReactiveJwtDecoder(String token, Mono<?> monoReturn) {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode(token)).willReturn(monoReturn);
return jwtDecoder;
}
Test Case ID #spring-security_Test_100_3
Test Case Name: decodeWhenInitializationInitiallyFailsThenRecoverable(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
- ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
+ ReactiveJwtDecoder jwtDecoder = createMockReactiveJwtDecoder("token", Mono.empty());
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
- given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierReactiveJwtDecoder.decode("token").block());
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierReactiveJwtDecoder.decode("token").block());
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private static ReactiveJwtDecoder createMockReactiveJwtDecoder(String token, Mono<?> monoReturn) {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode(token)).willReturn(monoReturn);
return jwtDecoder;
}
Mock Clone Instance #spring-security_MCI_101
- Scope: class level
- Mocked Class:
java.util.function.Predicate<org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockPredicateOidcUserRequest {
public static Predicate<OidcUserRequest> createMockPredicateOidcUserRequest(boolean testReturnValue) {
Predicate<OidcUserRequest> predicate = mock(Predicate.class);
given(predicate.test(any(OidcUserRequest.class))).willReturn(testReturnValue);
return predicate;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_101_1
Test Case Name: loadUserWhenCustomRetrieveUserInfoSetThenUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\userinfo\OidcReactiveOAuth2UserServiceTests.java)
Mock Object Variable Name: customRetrieveUserInfo
Suggested Diff
@@
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
- Predicate<OidcUserRequest> customRetrieveUserInfo = mock(Predicate.class);
- this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
- given(customRetrieveUserInfo.test(any(OidcUserRequest.class))).willReturn(true);
+ Predicate<OidcUserRequest> customRetrieveUserInfo = MockPredicateOidcUserRequest.createMockPredicateOidcUserRequest(true);
+ this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
// @formatter:off
OAuth2AccessToken accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), this.accessToken.getIssuedAt(), this.accessToken.getExpiresAt(), Collections.emptySet());
@@
Original Test Code (click to expand)
@Test
public void loadUserWhenCustomRetrieveUserInfoSetThenUsed() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(StandardClaimNames.SUB, "subject");
attributes.put("user", "steve");
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes, "user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
Predicate<OidcUserRequest> customRetrieveUserInfo = mock(Predicate.class);
this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
given(customRetrieveUserInfo.test(any(OidcUserRequest.class))).willReturn(true);
OAuth2AccessToken accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), this.accessToken.getIssuedAt(), this.accessToken.getExpiresAt(), Collections.emptySet());
OidcUserRequest userRequest = new OidcUserRequest(this.registration.build(), accessToken, this.idToken);
OidcUser oidcUser = this.userService.loadUser(userRequest).block();
assertThat(oidcUser).isNotNull();
assertThat(oidcUser.getUserInfo()).isNotNull();
verify(customRetrieveUserInfo).test(userRequest);
}
Reusable Method for MCI (click to expand)
public class MockPredicateOidcUserRequest {
public static Predicate<OidcUserRequest> createMockPredicateOidcUserRequest(boolean testReturnValue) {
Predicate<OidcUserRequest> predicate = mock(Predicate.class);
given(predicate.test(any(OidcUserRequest.class))).willReturn(testReturnValue);
return predicate;
}
}
Test Case ID #spring-security_Test_101_2
Test Case Name: loadUserWhenCustomRetrieveUserInfoSetThenUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\userinfo\OidcUserServiceTests.java)
Mock Object Variable Name: customRetrieveUserInfo
Suggested Diff
@@
this.accessToken = TestOAuth2AccessTokens.noScopes();
- Predicate<OidcUserRequest> customRetrieveUserInfo = mock(Predicate.class);
- given(customRetrieveUserInfo.test(any(OidcUserRequest.class))).willReturn(true);
+ Predicate<OidcUserRequest> customRetrieveUserInfo = MockPredicateOidcUserRequest.createMockPredicateOidcUserRequest(true);
this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
OidcUser user = this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void loadUserWhenCustomRetrieveUserInfoSetThenUsed() {
String userInfoResponse = "{\n" + " \"sub\": \"subject1\",\n" + " \"name\": \"first last\",\n" + " \"given_name\": \"first\",\n" + " \"family_name\": \"last\",\n" + " \"preferred_username\": \"user1\",\n" + " \"email\": \"user1@example.com\"\n" + "}\n";
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.accessToken = TestOAuth2AccessTokens.noScopes();
Predicate<OidcUserRequest> customRetrieveUserInfo = mock(Predicate.class);
given(customRetrieveUserInfo.test(any(OidcUserRequest.class))).willReturn(true);
this.userService.setRetrieveUserInfo(customRetrieveUserInfo);
OidcUser user = this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getUserInfo()).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockPredicateOidcUserRequest {
public static Predicate<OidcUserRequest> createMockPredicateOidcUserRequest(boolean testReturnValue) {
Predicate<OidcUserRequest> predicate = mock(Predicate.class);
given(predicate.test(any(OidcUserRequest.class))).willReturn(testReturnValue);
return predicate;
}
}
Mock Clone Instance #spring-security_MCI_102
- Scope: method level
- Mocked Class:
org.springframework.security.acls.model.ObjectIdentityRetrievalStrategy
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ObjectIdentityRetrievalStrategy createMockObjectIdentityRetrievalStrategy(ObjectIdentity oid) {
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
return oidStrategy;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_102_1
Test Case Name: hasPermissionReturnsTrueIfAclGrantsPermission(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: oidStrategy
Suggested Diff
@@
ObjectIdentity oid = mock(ObjectIdentity.class);
- ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
- given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
+ ObjectIdentityRetrievalStrategy oidStrategy = createMockObjectIdentityRetrievalStrategy(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
@@
Original Test Code (click to expand)
@Test
public void hasPermissionReturnsTrueIfAclGrantsPermission() {
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "READ")).isTrue();
}
Reusable Method for MCI (click to expand)
private static ObjectIdentityRetrievalStrategy createMockObjectIdentityRetrievalStrategy(ObjectIdentity oid) {
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
return oidStrategy;
}
Test Case ID #spring-security_Test_102_2
Test Case Name: resolvePermissionNonEnglishLocale(File: C:\Java_projects\Spring\spring-security\acl\src\test\java\org\springframework\security\acls\AclPermissionEvaluatorTests.java)
Mock Object Variable Name: oidStrategy
Suggested Diff
@@
ObjectIdentity oid = mock(ObjectIdentity.class);
- ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
- given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
+ ObjectIdentityRetrievalStrategy oidStrategy = createMockObjectIdentityRetrievalStrategy(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
@@
Original Test Code (click to expand)
@Test
public void resolvePermissionNonEnglishLocale() {
Locale systemLocale = Locale.getDefault();
Locale.setDefault(new Locale("tr"));
AclService service = mock(AclService.class);
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
ObjectIdentity oid = mock(ObjectIdentity.class);
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
Acl acl = mock(Acl.class);
given(service.readAclById(any(ObjectIdentity.class), anyList())).willReturn(acl);
given(acl.isGranted(anyList(), anyList(), eq(false))).willReturn(true);
assertThat(pe.hasPermission(mock(Authentication.class), new Object(), "write")).isTrue();
Locale.setDefault(systemLocale);
}
Reusable Method for MCI (click to expand)
private static ObjectIdentityRetrievalStrategy createMockObjectIdentityRetrievalStrategy(ObjectIdentity oid) {
ObjectIdentityRetrievalStrategy oidStrategy = mock(ObjectIdentityRetrievalStrategy.class);
given(oidStrategy.getObjectIdentity(any(Object.class))).willReturn(oid);
return oidStrategy;
}
Mock Clone Instance #spring-security_MCI_103
- Scope: method level
- Mocked Class:
org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository<org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository;
@BeforeEach
public void setUp() {
authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
}
authenticationRequestRepository
The refactoring details in each test cases
Test Case ID #spring-security_Test_103_1
Test Case Name: attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\Saml2WebSsoAuthenticationFilterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest() {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
+ // removed local mock; replaced with global field `authenticationRequestRepository`
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(this.request)).willReturn(TestSaml2AuthenticationTokens.token());
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.request.setRequestURI("/some/other/path/idp-registration-id");
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
this.filter.attemptAuthentication(this.request, this.response);
- verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response);
+ verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response);
}
Original Test Code (click to expand)
@Test
public void attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
given(authenticationConverter.convert(this.request)).willReturn(TestSaml2AuthenticationTokens.token());
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationManager((authentication) -> null);
this.request.setRequestURI("/some/other/path/idp-registration-id");
this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
this.filter.attemptAuthentication(this.request, this.response);
verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response);
}
Reusable Method for MCI (click to expand)
private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository;
@BeforeEach
public void setUp() {
authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
}
authenticationRequestRepository
Test Case ID #spring-security_Test_103_2
Test Case Name: setAuthenticationRequestRepositoryWhenExpectedAuthenticationConverterTypeThenSetLoaderIntoConverter(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\Saml2WebSsoAuthenticationFilterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void setAuthenticationRequestRepositoryWhenExpectedAuthenticationConverterTypeThenSetLoaderIntoConverter() {
Saml2AuthenticationTokenConverter authenticationConverter = mock(Saml2AuthenticationTokenConverter.class);
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
+ // removed local mock; replaced with global field `authenticationRequestRepository`
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
- this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
+ this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
- verify(authenticationConverter).setAuthenticationRequestRepository(authenticationRequestRepository);
+ verify(authenticationConverter).setAuthenticationRequestRepository(authenticationRequestRepository);
}
Original Test Code (click to expand)
@Test
public void setAuthenticationRequestRepositoryWhenExpectedAuthenticationConverterTypeThenSetLoaderIntoConverter() {
Saml2AuthenticationTokenConverter authenticationConverter = mock(Saml2AuthenticationTokenConverter.class);
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
verify(authenticationConverter).setAuthenticationRequestRepository(authenticationRequestRepository);
}
Reusable Method for MCI (click to expand)
private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository;
@BeforeEach
public void setUp() {
authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
}
authenticationRequestRepository
Test Case ID #spring-security_Test_103_3
Test Case Name: setAuthenticationRequestRepositoryWhenNotExpectedAuthenticationConverterTypeThenDoNotSet(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\authentication\Saml2WebSsoAuthenticationFilterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void setAuthenticationRequestRepositoryWhenNotExpectedAuthenticationConverterTypeThenDoNotSet() {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
+ // removed local mock; replaced with global field `authenticationRequestRepository`
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
- this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
+ this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
verifyNoInteractions(authenticationConverter);
}
Original Test Code (click to expand)
@Test
public void setAuthenticationRequestRepositoryWhenNotExpectedAuthenticationConverterTypeThenDoNotSet() {
AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class);
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}");
this.filter.setAuthenticationRequestRepository(authenticationRequestRepository);
verifyNoInteractions(authenticationConverter);
}
Reusable Method for MCI (click to expand)
private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository;
@BeforeEach
public void setUp() {
authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
}
authenticationRequestRepository
Mock Clone Instance #spring-security_MCI_104
- Scope: class level
- Mocked Class:
org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository<org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest>
- Test Case Count: 2
- MO Count: 5
Reusable Method
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_104_1
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml4AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = MockSaml2AuthenticationRequestRepository.createMockSaml2AuthenticationRequestRepository(authenticationRequest);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
- given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
Test Case ID #spring-security_Test_104_2
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\web\OpenSamlAuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = MockSaml2AuthenticationRequestRepository.createMockSaml2AuthenticationRequestRepository(authenticationRequest);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
- given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
Test Case ID #spring-security_Test_104_3
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\web\OpenSaml5AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = MockSaml2AuthenticationRequestRepository.createMockSaml2AuthenticationRequestRepository(authenticationRequest);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
- given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml5AuthenticationTokenConverter converter = new OpenSaml5AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
Test Case ID #spring-security_Test_104_4
Test Case Name: convertWhenSavedAuthenticationRequestThenToken(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
- given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = MockSaml2AuthenticationRequestRepository.createMockSaml2AuthenticationRequestRepository(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(this.relyingPartyRegistrationResolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
Reusable Method for MCI (click to expand)
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
Test Case ID #spring-security_Test_104_5
Test Case Name: convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\test\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverterTests.java)
Mock Object Variable Name: authenticationRequestRepository
Suggested Diff
@@
public void convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver(@Mock RelyingPartyRegistrationResolver resolver) {
- Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
+ Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = MockSaml2AuthenticationRequestRepository.createMockSaml2AuthenticationRequestRepository(authenticationRequest);
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
- given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
verify(resolver).resolve(any(), eq(this.relyingPartyRegistration.getRegistrationId()));
@@
Original Test Code (click to expand)
@Test
public void convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver(@Mock RelyingPartyRegistrationResolver resolver) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.relyingPartyRegistration.getRegistrationId());
Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(this.relyingPartyRegistration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
verify(resolver).resolve(any(), eq(this.relyingPartyRegistration.getRegistrationId()));
}
Reusable Method for MCI (click to expand)
public class MockSaml2AuthenticationRequestRepository {
public static Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> createMockSaml2AuthenticationRequestRepository(AbstractSaml2AuthenticationRequest authenticationRequest) {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(Saml2AuthenticationRequestRepository.class);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))).willReturn(authenticationRequest);
return authenticationRequestRepository;
}
}
Mock Clone Instance #spring-security_MCI_105
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static ReactiveOpaqueTokenIntrospector createMockReactiveOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(principal));
return introspector;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_105_1
Test Case Name: authenticateWhenActiveTokenThenOk(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
OAuth2AuthenticatedPrincipal authority = TestOAuth2AuthenticatedPrincipals.active((attributes) -> attributes.put("extension_field", "twenty-seven"));
- ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
- given(introspector.introspect(any())).willReturn(Mono.just(authority));
+ ReactiveOpaqueTokenIntrospector introspector = createMockReactiveOpaqueTokenIntrospector(authority);
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
// @formatter:off
assertThat(attributes).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")).containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4").containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)).containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")).containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis").containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe").containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin");
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenActiveTokenThenOk() throws Exception {
OAuth2AuthenticatedPrincipal authority = TestOAuth2AuthenticatedPrincipals.active((attributes) -> attributes.put("extension_field", "twenty-seven"));
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(authority));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true).containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")).containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4").containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)).containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")).containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)).containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")).containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis").containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe").containsEntry("extension_field", "twenty-seven");
assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin");
}
Reusable Method for MCI (click to expand)
private static ReactiveOpaqueTokenIntrospector createMockReactiveOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(principal));
return introspector;
}
Test Case ID #spring-security_Test_105_2
Test Case Name: authenticateWhenMissingScopeAttributeThenNoAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
OAuth2AuthenticatedPrincipal authority = new OAuth2IntrospectionAuthenticatedPrincipal(Collections.singletonMap("claim", "value"), null);
- ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
- given(introspector.introspect(any())).willReturn(Mono.just(authority));
+ ReactiveOpaqueTokenIntrospector introspector = createMockReactiveOpaqueTokenIntrospector(authority);
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
assertThat(result.getAuthorities()).isEmpty();
Original Test Code (click to expand)
@Test
public void authenticateWhenMissingScopeAttributeThenNoAuthorities() {
OAuth2AuthenticatedPrincipal authority = new OAuth2IntrospectionAuthenticatedPrincipal(Collections.singletonMap("claim", "value"), null);
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(authority));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class);
Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes();
assertThat(attributes).isNotNull().doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
assertThat(result.getAuthorities()).isEmpty();
}
Reusable Method for MCI (click to expand)
private static ReactiveOpaqueTokenIntrospector createMockReactiveOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(principal));
return introspector;
}
Test Case ID #spring-security_Test_105_3
Test Case Name: authenticateWhenCustomAuthenticationConverterThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-resource-server\src\test\java\org\springframework\security\oauth2\server\resource\authentication\OpaqueTokenReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: introspector
Suggested Diff
@@
public void authenticateWhenCustomAuthenticationConverterThenUses() {
- ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active();
- given(introspector.introspect(any())).willReturn(Mono.just(principal));
+ ReactiveOpaqueTokenIntrospector introspector = createMockReactiveOpaqueTokenIntrospector(principal);
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
ReactiveOpaqueTokenAuthenticationConverter authenticationConverter = mock(ReactiveOpaqueTokenAuthenticationConverter.class);
given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))).willReturn(Mono.just(new TestingAuthenticationToken(principal, null, Collections.emptyList())));
provider.setAuthenticationConverter(authenticationConverter);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result).isNotNull();
verify(introspector).introspect("token");
verify(authenticationConverter).convert("token", principal);
verifyNoMoreInteractions(introspector, authenticationConverter);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenCustomAuthenticationConverterThenUses() {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active();
given(introspector.introspect(any())).willReturn(Mono.just(principal));
OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector);
ReactiveOpaqueTokenAuthenticationConverter authenticationConverter = mock(ReactiveOpaqueTokenAuthenticationConverter.class);
given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))).willReturn(Mono.just(new TestingAuthenticationToken(principal, null, Collections.emptyList())));
provider.setAuthenticationConverter(authenticationConverter);
Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block();
assertThat(result).isNotNull();
verify(introspector).introspect("token");
verify(authenticationConverter).convert("token", principal);
verifyNoMoreInteractions(introspector, authenticationConverter);
}
Reusable Method for MCI (click to expand)
private static ReactiveOpaqueTokenIntrospector createMockReactiveOpaqueTokenIntrospector(OAuth2AuthenticatedPrincipal principal) {
ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class);
given(introspector.introspect(any())).willReturn(Mono.just(principal));
return introspector;
}
Mock Clone Instance #spring-security_MCI_106
- Scope: class level
- Mocked Class:
org.springframework.web.server.WebFilterChain
- Test Case Count: 9
- MO Count: 9
Reusable Method
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_106_1
Test Case Name: decorateWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verify(handler).onStart(any());
Original Test Code (click to expand)
@Test
void decorateWhenDefaultsThenObserves() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verify(handler).onStart(any());
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_2
Test Case Name: decorateWhenNoopThenDoesNotObserve(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verifyNoInteractions(handler);
@@
Original Test Code (click to expand)
@Test
void decorateWhenNoopThenDoesNotObserve() {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain);
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
verifyNoInteractions(handler);
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_3
Test Case Name: decorateWhenTerminatingFilterThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.error(() -> new Exception("ack")));
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.error(() -> new Exception("ack")));
WebFilterChain decorated = decorator.decorate(chain, List.of(new BasicAuthenticationFilter(), new TerminatingFilter()));
Observation http = Observation.start("http", registry).contextualName("http");
try {
Original Test Code (click to expand)
@Test
void decorateWhenTerminatingFilterThenObserves() {
AccumulatingObservationHandler handler = new AccumulatingObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.error(() -> new Exception("ack")));
WebFilterChain decorated = decorator.decorate(chain, List.of(new BasicAuthenticationFilter(), new TerminatingFilter()));
Observation http = Observation.start("http", registry).contextualName("http");
try {
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, http)).block();
} catch (Exception ex) {
http.error(ex);
} finally {
http.stop();
}
handler.assertSpanStart(0, "http", null);
handler.assertSpanStart(1, "spring.security.filterchains", "http");
handler.assertSpanStop(2, "security filterchain before");
handler.assertSpanStart(3, "spring.security.filterchains", "http");
handler.assertSpanStop(4, "security filterchain after");
handler.assertSpanStop(5, "http");
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_4
Test Case Name: decorateWhenErrorSignalThenStopsObservation(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.error(() -> new Exception("ack")));
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.error(() -> new Exception("ack")));
WebFilterChain decorated = decorator.decorate(chain, List.of(new BasicAuthenticationFilter()));
Observation http = Observation.start("http", registry).contextualName("http");
@@
Original Test Code (click to expand)
@Test
void decorateWhenErrorSignalThenStopsObservation() {
AccumulatingObservationHandler handler = new AccumulatingObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.error(() -> new Exception("ack")));
WebFilterChain decorated = decorator.decorate(chain, List.of(new BasicAuthenticationFilter()));
Observation http = Observation.start("http", registry).contextualName("http");
try {
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, http)).block();
} catch (Exception ex) {
http.error(ex);
} finally {
http.stop();
}
handler.assertSpanStart(0, "http", null);
handler.assertSpanStart(1, "spring.security.filterchains", "http");
handler.assertSpanStop(2, "security filterchain before");
handler.assertSpanStart(3, "secured request", "security filterchain before");
handler.assertSpanError(4);
handler.assertSpanStop(5, "secured request");
handler.assertSpanStart(6, "spring.security.filterchains", "http");
handler.assertSpanError(7);
handler.assertSpanStop(8, "security filterchain after");
handler.assertSpanError(9);
handler.assertSpanStop(10, "http");
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_5
Test Case Name: decorateWhenCustomAfterFilterThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\ObservationWebFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
WebFilter mock = mock(WebFilter.class);
given(mock.filter(any(), any())).willReturn(Mono.empty());
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of((e, c) -> c.filter(e).then(Mono.deferContextual((context) -> {
Observation parentObservation = context.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted("custom", registry).parentObservation(parentObservation).contextualName("custom").start();
return Mono.just("3").doOnSuccess((v) -> observation.stop()).doOnCancel(observation::stop).doOnError((t) -> {
observation.error(t);
observation.stop();
}).then(Mono.empty());
}))));
@@
Original Test Code (click to expand)
@Test
void decorateWhenCustomAfterFilterThenObserves() {
AccumulatingObservationHandler handler = new AccumulatingObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilter mock = mock(WebFilter.class);
given(mock.filter(any(), any())).willReturn(Mono.empty());
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of((e, c) -> c.filter(e).then(Mono.deferContextual((context) -> {
Observation parentObservation = context.getOrDefault(ObservationThreadLocalAccessor.KEY, null);
Observation observation = Observation.createNotStarted("custom", registry).parentObservation(parentObservation).contextualName("custom").start();
return Mono.just("3").doOnSuccess((v) -> observation.stop()).doOnCancel(observation::stop).doOnError((t) -> {
observation.error(t);
observation.stop();
}).then(Mono.empty());
}))));
Observation http = Observation.start("http", registry).contextualName("http");
try {
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).contextWrite((context) -> context.put(ObservationThreadLocalAccessor.KEY, http)).block();
} finally {
http.stop();
}
handler.assertSpanStart(0, "http", null);
handler.assertSpanStart(1, "spring.security.filterchains", "http");
handler.assertSpanStop(2, "security filterchain before");
handler.assertSpanStart(3, "secured request", "security filterchain before");
handler.assertSpanStop(4, "secured request");
handler.assertSpanStart(5, "spring.security.filterchains", "http");
handler.assertSpanStart(6, "custom", "spring.security.filterchains");
handler.assertSpanStop(7, "custom");
handler.assertSpanStop(8, "security filterchain after");
handler.assertSpanStop(9, "http");
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_6
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
- WebFilterChain chain = mock(WebFilterChain.class);
- given(chain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain chain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStop(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Original Test Code (click to expand)
@ParameterizedTest
@MethodSource("decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTagArguments")
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(WebFilter filter, String expectedFilterNameTag) {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStop(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_7
Test Case Name: doFilterWhenMatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: mockChain
Suggested Diff
@@
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
- WebFilterChain mockChain = mock(WebFilterChain.class);
- given(mockChain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain mockChain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenMatchesThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_8
Test Case Name: doFilterWhenMismatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: mockChain
Suggested Diff
@@
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
- WebFilterChain mockChain = mock(WebFilterChain.class);
- given(mockChain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain mockChain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenMismatchesThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Test Case ID #spring-security_Test_106_9
Test Case Name: doFilterWhenFilterExceptionThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: mockChain
Suggested Diff
@@
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
- WebFilterChain mockChain = mock(WebFilterChain.class);
- given(mockChain.filter(any())).willReturn(Mono.empty());
+ WebFilterChain mockChain = MockWebFilterChain.createMockWebFilterChain(Mono.empty());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block());
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
WebFilter error = mock(WebFilter.class);
given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException()));
List<WebFilter> filters = Arrays.asList(error);
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block());
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Reusable Method for MCI (click to expand)
public class MockWebFilterChain {
public static WebFilterChain createMockWebFilterChain(Mono<?> filterReturn) {
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(filterReturn);
return chain;
}
}
Mock Clone Instance #spring-security_MCI_107
- Scope: method level
- Mocked Class:
org.springframework.web.server.WebFilterChain
- Test Case Count: 8
- MO Count: 8
Reusable Method
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
The refactoring details in each test cases
Test Case ID #spring-security_Test_107_1
Test Case Name: switchUser(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void switchUser() {
final String targetUsername = "TEST_USERNAME";
final UserDetails switchUserDetails = switchUserDetails(targetUsername, true);
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("principal", "credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
verify(this.userDetailsService).findByUsername(targetUsername);
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication switchUserAuthentication = authenticationCaptor.getValue();
assertThat(switchUserAuthentication).isSameAs(savedSecurityContext.getAuthentication());
assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR));
assertThat(switchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)).contains(originalAuthentication.getName());
}
Original Test Code (click to expand)
@Test
public void switchUser() {
final String targetUsername = "TEST_USERNAME";
final UserDetails switchUserDetails = switchUserDetails(targetUsername, true);
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("principal", "credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
verify(this.userDetailsService).findByUsername(targetUsername);
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication switchUserAuthentication = authenticationCaptor.getValue();
assertThat(switchUserAuthentication).isSameAs(savedSecurityContext.getAuthentication());
assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR));
assertThat(switchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)).contains(originalAuthentication.getName());
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_2
Test Case Name: switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
final String targetUsername = "newSwitchPrincipal";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails(targetUsername, true)));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue();
assertThat(secondSwitchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(secondSwitchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName).findFirst().orElse(null)).isEqualTo(originalAuthentication.getName());
Original Test Code (click to expand)
@Test
public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() {
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken.authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
final String targetUsername = "newSwitchPrincipal";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails(targetUsername, true)));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue();
assertThat(secondSwitchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(secondSwitchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName).findFirst().orElse(null)).isEqualTo(originalAuthentication.getName());
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_3
Test Case Name: switchUserWhenUsernameIsMissingThenThrowException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void switchUserWhenUsernameIsMissingThenThrowException() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate"));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
assertThatIllegalArgumentException().isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
}).withMessage("The userName can not be null.");
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void switchUserWhenUsernameIsMissingThenThrowException() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate"));
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
assertThatIllegalArgumentException().isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
}).withMessage("The userName can not be null.");
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_4
Test Case Name: switchUserWhenExceptionThenCallFailureHandler(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void switchUserWhenExceptionThenCallFailureHandler() {
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
given(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class));
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void switchUserWhenExceptionThenCallFailureHandler() {
final String targetUsername = "TEST_USERNAME";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
given(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class));
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_5
Test Case Name: switchUserWhenFailureHandlerNotDefinedThenReturnError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void switchUserWhenFailureHandlerNotDefinedThenReturnError() {
this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, null);
final String targetUsername = "TEST_USERNAME";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
});
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void switchUserWhenFailureHandlerNotDefinedThenReturnError() {
this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, null);
final String targetUsername = "TEST_USERNAME";
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
});
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_6
Test Case Name: exitSwitchThenReturnToOriginalAuthentication(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void exitSwitchThenReturnToOriginalAuthentication() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken.authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication originalAuthenticationValue = authenticationCaptor.getValue();
assertThat(savedSecurityContext.getAuthentication()).isSameAs(originalAuthentication);
assertThat(originalAuthenticationValue).isSameAs(originalAuthentication);
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void exitSwitchThenReturnToOriginalAuthentication() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("origPrincipal", "origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = UsernamePasswordAuthenticationToken.authenticated("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
this.switchUserWebFilter.filter(exchange, chain).contextWrite(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
final Authentication originalAuthenticationValue = authenticationCaptor.getValue();
assertThat(savedSecurityContext.getAuthentication()).isSameAs(originalAuthentication);
assertThat(originalAuthenticationValue).isSameAs(originalAuthentication);
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_7
Test Case Name: exitSwitchWhenUserNotSwitchedThenThrowError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void exitSwitchWhenUserNotSwitchedThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("origPrincipal", "origCredentials");
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
}).withMessage("Could not find original Authentication object");
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void exitSwitchWhenUserNotSwitchedThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
final Authentication originalAuthentication = UsernamePasswordAuthenticationToken.unauthenticated("origPrincipal", "origCredentials");
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> {
Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
this.switchUserWebFilter.filter(exchange, chain).contextWrite(securityContextHolder).block();
}).withMessage("Could not find original Authentication object");
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Test Case ID #spring-security_Test_107_8
Test Case Name: exitSwitchWhenNoCurrentUserThenThrowError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\SwitchUserWebFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void exitSwitchWhenNoCurrentUserThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
- final WebFilterChain chain = mock(WebFilterChain.class);
+ // removed local mock; replaced with global field `chain`
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> this.switchUserWebFilter.filter(exchange, chain).block()).withMessage("No current user associated with this request");
verifyNoInteractions(chain);
}
Original Test Code (click to expand)
@Test
public void exitSwitchWhenNoCurrentUserThenThrowError() {
final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
final WebFilterChain chain = mock(WebFilterChain.class);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> this.switchUserWebFilter.filter(exchange, chain).block()).withMessage("No current user associated with this request");
verifyNoInteractions(chain);
}
Reusable Method for MCI (click to expand)
private WebFilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(WebFilterChain.class);
}
chain
Mock Clone Instance #spring-security_MCI_108
- Scope: class level
- Mocked Class:
org.springframework.core.io.ResourceLoader
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockResourceLoader {
public static ResourceLoader createMockResourceLoader(String classPathResourceName) {
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(any())).willReturn(new ClassPathResource(classPathResourceName));
return resourceLoader;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_108_1
Mock Object Variable Name: resourceLoader
Suggested Diff
@@
public void withTrustedMetadataLocationWhenCustomResourceLoaderThenUses() {
- ResourceLoader resourceLoader = mock(ResourceLoader.class);
- given(resourceLoader.getResource(any())).willReturn(new ClassPathResource("test-metadata.xml"));
+ ResourceLoader resourceLoader = MockResourceLoader.createMockResourceLoader("test-metadata.xml");
AssertingPartyMetadata party = OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:wrong").resourceLoader(resourceLoader).build().iterator().next();
assertThat(party.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth");
assertThat(party.getSingleSignOnServiceLocation()).isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO");
assertThat(party.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(party.getVerificationX509Credentials()).hasSize(1);
assertThat(party.getEncryptionX509Credentials()).hasSize(1);
verify(resourceLoader).getResource(any());
@@
Original Test Code (click to expand)
@Test
public void withTrustedMetadataLocationWhenCustomResourceLoaderThenUses() {
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(any())).willReturn(new ClassPathResource("test-metadata.xml"));
AssertingPartyMetadata party = OpenSaml4AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:wrong").resourceLoader(resourceLoader).build().iterator().next();
assertThat(party.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth");
assertThat(party.getSingleSignOnServiceLocation()).isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO");
assertThat(party.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(party.getVerificationX509Credentials()).hasSize(1);
assertThat(party.getEncryptionX509Credentials()).hasSize(1);
verify(resourceLoader).getResource(any());
}
Reusable Method for MCI (click to expand)
public class MockResourceLoader {
public static ResourceLoader createMockResourceLoader(String classPathResourceName) {
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(any())).willReturn(new ClassPathResource(classPathResourceName));
return resourceLoader;
}
}
Test Case ID #spring-security_Test_108_2
Mock Object Variable Name: resourceLoader
Suggested Diff
@@
@Test
public void withTrustedMetadataLocationWhenCustomResourceLoaderThenUses() {
- ResourceLoader resourceLoader = mock(ResourceLoader.class);
- given(resourceLoader.getResource(any())).willReturn(new ClassPathResource("test-metadata.xml"));
+ ResourceLoader resourceLoader = MockResourceLoader.createMockResourceLoader("test-metadata.xml");
AssertingPartyMetadata party = OpenSaml5AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:wrong").resourceLoader(resourceLoader).build().iterator().next();
assertThat(party.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth");
assertThat(party.getSingleSignOnServiceLocation()).isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO");
assertThat(party.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(party.getVerificationX509Credentials()).hasSize(1);
assertThat(party.getEncryptionX509Credentials()).hasSize(1);
verify(resourceLoader).getResource(any());
}
@@
Original Test Code (click to expand)
@Test
public void withTrustedMetadataLocationWhenCustomResourceLoaderThenUses() {
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(any())).willReturn(new ClassPathResource("test-metadata.xml"));
AssertingPartyMetadata party = OpenSaml5AssertingPartyMetadataRepository.withTrustedMetadataLocation("classpath:wrong").resourceLoader(resourceLoader).build().iterator().next();
assertThat(party.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth");
assertThat(party.getSingleSignOnServiceLocation()).isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO");
assertThat(party.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST);
assertThat(party.getVerificationX509Credentials()).hasSize(1);
assertThat(party.getEncryptionX509Credentials()).hasSize(1);
verify(resourceLoader).getResource(any());
}
Reusable Method for MCI (click to expand)
public class MockResourceLoader {
public static ResourceLoader createMockResourceLoader(String classPathResourceName) {
ResourceLoader resourceLoader = mock(ResourceLoader.class);
given(resourceLoader.getResource(any())).willReturn(new ClassPathResource(classPathResourceName));
return resourceLoader;
}
}
Mock Clone Instance #spring-security_MCI_109
- Scope: method level
- Mocked Class:
java.util.function.Supplier<org.springframework.security.oauth2.jwt.JwtDecoder>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Supplier<JwtDecoder> createMockBrokenSupplier() {
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_109_1
Test Case Name: decodeWhenInitializationFailsThenInitializationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierJwtDecoderTests.java)
Mock Object Variable Name: broken
Suggested Diff
@@
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
- Supplier<JwtDecoder> broken = mock(Supplier.class);
- given(broken.get()).willThrow(RuntimeException.class);
+ Supplier<JwtDecoder> broken = createMockBrokenSupplier();
JwtDecoder jwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> jwtDecoder.decode("token"));
verify(broken).get();
}
@@
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder jwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> jwtDecoder.decode("token"));
verify(broken).get();
}
Reusable Method for MCI (click to expand)
private static Supplier<JwtDecoder> createMockBrokenSupplier() {
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
Test Case ID #spring-security_Test_109_2
Test Case Name: decodeWhenInitializationInitiallyFailsThenRecoverable(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierJwtDecoderTests.java)
Mock Object Variable Name: broken
Suggested Diff
@@
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
- Supplier<JwtDecoder> broken = mock(Supplier.class);
- given(broken.get()).willThrow(RuntimeException.class);
+ Supplier<JwtDecoder> broken = createMockBrokenSupplier();
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierJwtDecoder.decode("token"));
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
@@
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierJwtDecoder.decode("token"));
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private static Supplier<JwtDecoder> createMockBrokenSupplier() {
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
return broken;
}
Mock Clone Instance #spring-security_MCI_110
- Scope: class level
- Mocked Class:
org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider
- Test Case Count: 3
- MO Count: 5
Reusable Method
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_110_1
Test Case Name: authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\DelegatingReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: authorizedClientProvider1
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), TestOAuth2AccessTokens.noScopes());
- ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
- given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
+ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = MockReactiveOAuth2AuthorizedClientProvider.createMockReactiveOAuth2AuthorizedClientProvider(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient));
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient() {
Authentication principal = new TestingAuthenticationToken("principal", "password");
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), TestOAuth2AccessTokens.noScopes());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient));
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(principal).build();
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context).block();
assertThat(reauthorizedClient).isSameAs(authorizedClient);
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
Test Case ID #spring-security_Test_110_2
Test Case Name: authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\DelegatingReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: authorizedClientProvider2
Suggested Diff
@@
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
- ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
- given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
+ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = MockReactiveOAuth2AuthorizedClientProvider.createMockReactiveOAuth2AuthorizedClientProvider(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient));
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient() {
Authentication principal = new TestingAuthenticationToken("principal", "password");
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(), TestOAuth2AccessTokens.noScopes());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient));
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(principal).build();
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context).block();
assertThat(reauthorizedClient).isSameAs(authorizedClient);
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
Test Case ID #spring-security_Test_110_3
Test Case Name: authorizeWhenProviderCantAuthorizeThenReturnNull(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\DelegatingReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: authorizedClientProvider1
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(new TestingAuthenticationToken("principal", "password")).build();
- ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
- given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
+ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = MockReactiveOAuth2AuthorizedClientProvider.createMockReactiveOAuth2AuthorizedClientProvider(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2);
assertThat(delegate.authorize(context).block()).isNull();
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(new TestingAuthenticationToken("principal", "password")).build();
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2);
assertThat(delegate.authorize(context).block()).isNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
Test Case ID #spring-security_Test_110_4
Test Case Name: authorizeWhenProviderCantAuthorizeThenReturnNull(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\DelegatingReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: authorizedClientProvider2
Suggested Diff
@@
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
- ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
- given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
+ ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = MockReactiveOAuth2AuthorizedClientProvider.createMockReactiveOAuth2AuthorizedClientProvider(Mono.empty());
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2);
assertThat(delegate.authorize(context).block()).isNull();
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration).principal(new TestingAuthenticationToken("principal", "password")).build();
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(authorizedClientProvider1, authorizedClientProvider2);
assertThat(delegate.authorize(context).block()).isNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
Test Case ID #spring-security_Test_110_5
Test Case Name: buildWhenCustomProviderThenProviderCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\ReactiveOAuth2AuthorizedClientProviderBuilderTests.java)
Mock Object Variable Name: customProvider
Suggested Diff
@@
@Test
public void buildWhenCustomProviderThenProviderCalled() {
- ReactiveOAuth2AuthorizedClientProvider customProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
- given(customProvider.authorize(any())).willReturn(Mono.empty());
+ ReactiveOAuth2AuthorizedClientProvider customProvider = MockReactiveOAuth2AuthorizedClientProvider.createMockReactiveOAuth2AuthorizedClientProvider(Mono.empty());
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(customProvider).build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
// @formatter:on
authorizedClientProvider.authorize(authorizationContext).block();
verify(customProvider).authorize(any(OAuth2AuthorizationContext.class));
}
@@
Original Test Code (click to expand)
@Test
public void buildWhenCustomProviderThenProviderCalled() {
ReactiveOAuth2AuthorizedClientProvider customProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(customProvider.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(customProvider).build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
authorizedClientProvider.authorize(authorizationContext).block();
verify(customProvider).authorize(any(OAuth2AuthorizationContext.class));
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AuthorizedClientProvider {
public static ReactiveOAuth2AuthorizedClientProvider createMockReactiveOAuth2AuthorizedClientProvider(Mono<?> authorizeReturn) {
ReactiveOAuth2AuthorizedClientProvider mockProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(mockProvider.authorize(any())).willReturn(authorizeReturn);
return mockProvider;
}
}
Mock Clone Instance #spring-security_MCI_111
- Scope: class level
- Mocked Class:
java.util.function.Function<org.springframework.security.oauth2.client.registration.ClientRegistration, org.springframework.core.convert.converter.Converter<java.util.Map<java.lang.String, java.lang.Object>, java.util.Map<java.lang.String, java.lang.Object>>>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockCustomClaimTypeConverterFactory {
public static Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> createMockCustomClaimTypeConverterFactory(ClientRegistration clientRegistration, ClaimTypeConverter claimTypeConverter) {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(claimTypeConverter);
return customClaimTypeConverterFactory;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_111_1
Test Case Name: createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customClaimTypeConverterFactory
Suggested Diff
@@
@Test
public void createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied() {
- Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
- given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
+ Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = MockCustomClaimTypeConverterFactory.createMockCustomClaimTypeConverterFactory(
+ clientRegistration,
+ new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters())
+ );
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
@@
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied() {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockCustomClaimTypeConverterFactory {
public static Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> createMockCustomClaimTypeConverterFactory(ClientRegistration clientRegistration, ClaimTypeConverter claimTypeConverter) {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(claimTypeConverter);
return customClaimTypeConverterFactory;
}
}
Test Case ID #spring-security_Test_111_2
Test Case Name: createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\ReactiveOidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customClaimTypeConverterFactory
Suggested Diff
@@
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
- given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
+ Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = MockCustomClaimTypeConverterFactory.createMockCustomClaimTypeConverterFactory(
+ clientRegistration,
+ new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
+ this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
@@
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomClaimTypeConverterFactorySetThenApplied() {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
this.idTokenDecoderFactory.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(new ClaimTypeConverter(OidcIdTokenDecoderFactory.createDefaultClaimTypeConverters()));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockCustomClaimTypeConverterFactory {
public static Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> createMockCustomClaimTypeConverterFactory(ClientRegistration clientRegistration, ClaimTypeConverter claimTypeConverter) {
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(claimTypeConverter);
return customClaimTypeConverterFactory;
}
}
Mock Clone Instance #spring-security_MCI_112
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.method.AuthorizationManagerAfterReactiveMethodInterceptorTests.HandlingReactiveAuthorizationManager
- Test Case Count: 5
- MO Count: 5
Reusable Method
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_112_1
Test Case Name: invokeFluxWhenAllValuesDeniedAndPostProcessorThenPostProcessorAppliedToEachValueEmitted(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john-masked", "bob-masked");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenAllValuesDeniedAndPostProcessorThenPostProcessorAppliedToEachValueEmitted() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john-masked", "bob-masked");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_112_2
Test Case Name: invokeFluxWhenOneValueDeniedAndPostProcessorThenPostProcessorAppliedToDeniedValue(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer((invocation) -> {
- MethodInvocationResult argument = invocation.getArgument(0);
- if (!"john".equals(argument.getResult())) {
- return monoMasking(invocation);
- }
- return Mono.just(argument.getResult());
- });
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer((invocation) -> {
+ MethodInvocationResult argument = invocation.getArgument(0);
+ if (!"john".equals(argument.getResult())) {
+ return monoMasking(invocation);
+ }
+ return Mono.just(argument.getResult());
+ });
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob-masked");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenOneValueDeniedAndPostProcessorThenPostProcessorAppliedToDeniedValue() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer((invocation) -> {
MethodInvocationResult argument = invocation.getArgument(0);
if (!"john".equals(argument.getResult())) {
return monoMasking(invocation);
}
return Mono.just(argument.getResult());
});
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob-masked");
verify(mockReactiveAuthorizationManager, times(2)).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_112_3
Test Case Name: invokeMonoWhenPostProcessableDecisionThenPostProcess(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john-masked");
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenPostProcessableDecisionThenPostProcess() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::masking);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john-masked");
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_112_4
Test Case Name: invokeMonoWhenPostProcessableDecisionAndPostProcessResultIsMonoThenPostProcessWorks(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::monoMasking);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::monoMasking);
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john-masked");
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenPostProcessableDecisionAndPostProcessResultIsMonoThenPostProcessWorks() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willAnswer(this::monoMasking);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john-masked");
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_112_5
Test Case Name: invokeMonoWhenPostProcessableDecisionAndPostProcessResultIsNullThenPostProcessWorks(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerAfterReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willReturn(null);
- given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = createMockHandlingReactiveAuthorizationManager(Mono.empty());
+ given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willReturn(null);
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo(null);
verify(mockReactiveAuthorizationManager).check(any(), any());
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenPostProcessableDecisionAndPostProcessResultIsNullThenPostProcessWorks() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.handleDeniedInvocationResult(any(), any(AuthorizationResult.class))).willReturn(null);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerAfterReactiveMethodInterceptor interceptor = new AuthorizationManagerAfterReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo(null);
verify(mockReactiveAuthorizationManager).check(any(), any());
}
Reusable Method for MCI (click to expand)
private static HandlingReactiveAuthorizationManager createMockHandlingReactiveAuthorizationManager(Mono<?> checkReturn) {
HandlingReactiveAuthorizationManager mockReactiveAuthorizationManager = mock(HandlingReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), any())).willReturn(checkReturn);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_113
- Scope: method level
- Mocked Class:
org.springframework.web.context.WebApplicationContext
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static WebApplicationContext createMockWebApplicationContextWithSecurityContextHolderStrategyNames(String[] beanNames) {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(beanNames);
return wac;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_113_1
Test Case Name: privilegeEvaluatorFromRequest(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: wac
Suggested Diff
@@
@Test
public void privilegeEvaluatorFromRequest() throws IOException {
- WebApplicationContext wac = mock(WebApplicationContext.class);
+ WebApplicationContext wac = createMockWebApplicationContextWithSecurityContextHolderStrategyNames(new String[0]);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
- given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
@@
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromRequest() throws IOException {
WebApplicationContext wac = mock(WebApplicationContext.class);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
Reusable Method for MCI (click to expand)
private static WebApplicationContext createMockWebApplicationContextWithSecurityContextHolderStrategyNames(String[] beanNames) {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(beanNames);
return wac;
}
Test Case ID #spring-security_Test_113_2
Test Case Name: privilegeEvaluatorFromChildContext(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: wac
Suggested Diff
@@
this.tag.setUrl(uri);
- WebApplicationContext wac = mock(WebApplicationContext.class);
- given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).willReturn(Collections.singletonMap("wipe", expected));
- given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
+ WebApplicationContext wac = createMockWebApplicationContextWithSecurityContextHolderStrategyNames(new String[0]);
+ given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).willReturn(Collections.singletonMap("wipe", expected));
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
@@
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromChildContext() throws IOException {
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).willReturn(Collections.singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
Reusable Method for MCI (click to expand)
private static WebApplicationContext createMockWebApplicationContextWithSecurityContextHolderStrategyNames(String[] beanNames) {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(beanNames);
return wac;
}
Test Case ID #spring-security_Test_113_3
Test Case Name: expressionFromChildContext(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: wac
Suggested Diff
@@
this.tag.setAccess("permitAll");
- WebApplicationContext wac = mock(WebApplicationContext.class);
- given(wac.getBeansOfType(SecurityExpressionHandler.class)).willReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
- given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
+ WebApplicationContext wac = createMockWebApplicationContextWithSecurityContextHolderStrategyNames(new String[0]);
+ given(wac.getBeansOfType(SecurityExpressionHandler.class)).willReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
assertThat(this.tag.authorize()).isTrue();
}
Original Test Code (click to expand)
@Test
@SuppressWarnings("rawtypes")
public void expressionFromChildContext() throws IOException {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass", "USER"));
DefaultWebSecurityExpressionHandler expected = new DefaultWebSecurityExpressionHandler();
this.tag.setAccess("permitAll");
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(SecurityExpressionHandler.class)).willReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
assertThat(this.tag.authorize()).isTrue();
}
Reusable Method for MCI (click to expand)
private static WebApplicationContext createMockWebApplicationContextWithSecurityContextHolderStrategyNames(String[] beanNames) {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(beanNames);
return wac;
}
Mock Clone Instance #spring-security_MCI_114
- Scope: method level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Converter<OAuth2PasswordGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2PasswordGrantRequest request, HttpHeaders headers) {
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_114_1
Suggested Diff
@@
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
- Converter<OAuth2PasswordGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(addedHeadersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2PasswordGrantRequest, HttpHeaders> addedHeadersConverter = createMockHeadersConverter(request, headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
Converter<OAuth2PasswordGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
private static Converter<OAuth2PasswordGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2PasswordGrantRequest request, HttpHeaders headers) {
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
Test Case ID #spring-security_Test_114_2
Suggested Diff
@@
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
ClientRegistration clientRegistration = request.getClientRegistration();
- Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
- given(headersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = createMockHeadersConverter(request, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2PasswordGrantRequest request = new OAuth2PasswordGrantRequest(this.clientRegistrationBuilder.build(), this.username, this.password);
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Reusable Method for MCI (click to expand)
private static Converter<OAuth2PasswordGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2PasswordGrantRequest request, HttpHeaders headers) {
Converter<OAuth2PasswordGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
Mock Clone Instance #spring-security_MCI_115
- Scope: method level
- Mocked Class:
java.util.function.Function<org.springframework.security.oauth2.client.OAuth2AuthorizationContext, org.springframework.security.oauth2.core.OAuth2Token>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Function<OAuth2AuthorizationContext, OAuth2Token> createMockTokenResolver(OAuth2Token tokenToReturn) {
Function<OAuth2AuthorizationContext, OAuth2Token> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenToReturn);
return tokenResolver;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_115_1
Test Case Name: authorizeWhenCustomSubjectTokenResolverSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: subjectTokenResolver
Suggested Diff
@@
public void authorizeWhenCustomSubjectTokenResolverSetThenCalled() {
- Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver = mock(Function.class);
- given(subjectTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(this.subjectToken);
+ Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver = createMockTokenResolver(this.subjectToken);
this.authorizedClientProvider.setSubjectTokenResolver(subjectTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(accessTokenResponse);
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(subjectTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isNull();
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenCustomSubjectTokenResolverSetThenCalled() {
Function<OAuth2AuthorizationContext, OAuth2Token> subjectTokenResolver = mock(Function.class);
given(subjectTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(this.subjectToken);
this.authorizedClientProvider.setSubjectTokenResolver(subjectTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(accessTokenResponse);
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(subjectTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isNull();
}
Reusable Method for MCI (click to expand)
private static Function<OAuth2AuthorizationContext, OAuth2Token> createMockTokenResolver(OAuth2Token tokenToReturn) {
Function<OAuth2AuthorizationContext, OAuth2Token> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenToReturn);
return tokenResolver;
}
Test Case ID #spring-security_Test_115_2
Test Case Name: authorizeWhenCustomActorTokenResolverSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: actorTokenResolver
Suggested Diff
@@
public void authorizeWhenCustomActorTokenResolverSetThenCalled() {
- Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver = mock(Function.class);
- given(actorTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(this.actorToken);
+ Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver = createMockTokenResolver(this.actorToken);
this.authorizedClientProvider.setActorTokenResolver(actorTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(actorTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isEqualTo(this.actorToken);
}
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenCustomActorTokenResolverSetThenCalled() {
Function<OAuth2AuthorizationContext, OAuth2Token> actorTokenResolver = mock(Function.class);
given(actorTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(this.actorToken);
this.authorizedClientProvider.setActorTokenResolver(actorTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(accessTokenResponse);
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(actorTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isEqualTo(this.actorToken);
}
Reusable Method for MCI (click to expand)
private static Function<OAuth2AuthorizationContext, OAuth2Token> createMockTokenResolver(OAuth2Token tokenToReturn) {
Function<OAuth2AuthorizationContext, OAuth2Token> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenToReturn);
return tokenResolver;
}
Mock Clone Instance #spring-security_MCI_116
- Scope: class level
- Mocked Class:
org.springframework.security.web.util.matcher.RequestMatcher
- Test Case Count: 12
- MO Count: 15
Reusable Method
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_116_1
Test Case Name: matchesSingleTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleTrue() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_2
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
given(this.delegate2.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_3
Test Case Name: matchesSingleFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleFalse() {
- given(this.delegate.matches(this.request)).willReturn(false);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_4
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
- given(this.delegate.matches(this.request)).willReturn(false);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_5
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_6
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
- given(this.delegate2.matches(this.request)).willReturn(true);
+ this.delegate2 = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(true);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_7
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(true);
- given(this.delegate2.matches(this.request)).willReturn(false);
+ this.delegate2 = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(true);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_8
Test Case Name: matchesDelegateFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\NegatedRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesDelegateFalse() {
- given(this.delegate.matches(this.request)).willReturn(false);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesDelegateFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_9
Test Case Name: matchesDelegateTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\NegatedRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesDelegateTrue() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesDelegateTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new NegatedRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_10
Test Case Name: matchesSingleTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleTrue() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesSingleTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_11
Test Case Name: matchesMultiTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiTrue() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiTrue() {
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_12
Test Case Name: matchesSingleFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesSingleFalse() {
- given(this.delegate.matches(this.request)).willReturn(false);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_13
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
- given(this.delegate.matches(this.request)).willReturn(false);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, false);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_14
Test Case Name: matchesMultiSingleFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
@Test
public void matchesMultiSingleFalse() {
- given(this.delegate.matches(this.request)).willReturn(true);
+ this.delegate = MockRequestMatcher.createMockRequestMatcher(this.request, true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Original Test Code (click to expand)
@Test
public void matchesMultiSingleFalse() {
given(this.delegate.matches(this.request)).willReturn(true);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Test Case ID #spring-security_Test_116_15
Test Case Name: matchesMultiBothFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
- given(this.delegate2.matches(this.request)).willReturn(false);
+ this.delegate2 = MockRequestMatcher.createMockRequestMatcher(this.request, false);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Original Test Code (click to expand)
@Test
public void matchesMultiBothFalse() {
given(this.delegate.matches(this.request)).willReturn(false);
given(this.delegate2.matches(this.request)).willReturn(false);
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
assertThat(this.matcher.matches(this.request)).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matches(request)).willReturn(matchesReturn);
return mock;
}
}
Mock Clone Instance #spring-security_MCI_117
- Scope: class level
- Mocked Class:
org.springframework.security.web.util.matcher.RequestMatcher
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, MatchResult matchResult) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matcher(request)).willReturn(matchResult);
return mock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_117_1
Test Case Name: matcherWhenMatchersHavePlaceholdersThenPropagatesFirstMatch(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
+ // Cannot refactor this mock: The test intentionally re-stubs the same method on the mock multiple times with different return values, separated by assertions and verifications. The reusable helper only supports a single stub per mock instance, but the test requires changing the stubbed behavior at runtime. Refactoring would break the test's logic.
@@
Original Test Code (click to expand)
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesFirstMatch() {
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.notMatch());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, MatchResult matchResult) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matcher(request)).willReturn(matchResult);
return mock;
}
}
Test Case ID #spring-security_Test_117_2
Test Case Name: matcherWhenMatchersHavePlaceholdersThenPropagatesFirstMatch(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\OrRequestMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
- given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
+ // Cannot refactor this mock: The test method stubs delegate2.matcher(this.request) multiple times with different return values, separated by logic (calls to matcher and assertions). According to Rule 5A, these are intentional overrides and cannot be safely collapsed into a single helper call. The helper method only sets up a single stub, but the test requires changing the stub multiple times during execution.
MatchResult result = this.matcher.matcher(this.request);
Original Test Code (click to expand)
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesFirstMatch() {
this.matcher = new OrRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
verifyNoInteractions(this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.notMatch());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, MatchResult matchResult) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matcher(request)).willReturn(matchResult);
return mock;
}
}
Test Case ID #spring-security_Test_117_3
Test Case Name: matcherWhenMatchersHavePlaceholdersThenPropagatesMatches(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate
Suggested Diff
@@
+ // Cannot refactor this mock: The test method intentionally re-stubs the same mock multiple times with different values, separated by assertions and logic. The reusable helper only sets a single stub at creation, but the test requires changing the stubbed return value of delegate.matcher(this.request) multiple times during execution. Refactoring to use the helper would break the test's logic.
@@
Original Test Code (click to expand)
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesMatches() {
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "othervalue"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.notMatch());
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("otherparam", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyInAnyOrderEntriesOf(Map.of("otherparam", "value", "param", "value"));
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, MatchResult matchResult) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matcher(request)).willReturn(matchResult);
return mock;
}
}
Test Case ID #spring-security_Test_117_4
Test Case Name: matcherWhenMatchersHavePlaceholdersThenPropagatesMatches(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\util\matcher\AndRequestMatcherTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
+ // Cannot refactor this mock: The test method repeatedly stubs delegate2.matcher(this.request) with different return values between assertions. The reusable helper only supports a single stub per mock instance, but the test intentionally overrides the stub multiple times to test different behaviors. Refactoring with the helper would break the test's logic.
@@
Original Test Code (click to expand)
@Test
public void matcherWhenMatchersHavePlaceholdersThenPropagatesMatches() {
this.matcher = new AndRequestMatcher(this.delegate, this.delegate2);
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "othervalue")));
MatchResult result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "othervalue"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match());
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyEntriesOf(Map.of("param", "value"));
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.notMatch());
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).isEmpty();
given(this.delegate.matcher(this.request)).willReturn(MatchResult.match(Map.of("otherparam", "value")));
given(this.delegate2.matcher(this.request)).willReturn(MatchResult.match(Map.of("param", "value")));
result = this.matcher.matcher(this.request);
assertThat(result.getVariables()).containsExactlyInAnyOrderEntriesOf(Map.of("otherparam", "value", "param", "value"));
}
Reusable Method for MCI (click to expand)
public class MockRequestMatcher {
public static RequestMatcher createMockRequestMatcher(HttpServletRequest request, MatchResult matchResult) {
RequestMatcher mock = mock(RequestMatcher.class);
given(mock.matcher(request)).willReturn(matchResult);
return mock;
}
}
Mock Clone Instance #spring-security_MCI_118
- Scope: method level
- Mocked Class:
org.springframework.security.web.util.matcher.RequestMatcher
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static RequestMatcher createMockRequestMatcher(boolean matchesReturn, HttpServletRequest request) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_118_1
Test Case Name: onLogoutSuccessFirstMatches(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\logout\DelegatingLogoutSuccessHandlerTests.java)
Mock Object Variable Name: matcher
Suggested Diff
@@
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
- given(this.matcher.matches(this.request)).willReturn(true);
+ this.matcher = createMockRequestMatcher(true, this.request);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler).onLogoutSuccess(this.request, this.response, this.authentication);
verifyNoMoreInteractions(this.matcher2, this.handler2, this.defaultHandler);
Original Test Code (click to expand)
@BeforeEach
public void setup() {
LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>();
matcherToHandler.put(this.matcher, this.handler);
matcherToHandler.put(this.matcher2, this.handler2);
this.delegatingHandler = new DelegatingLogoutSuccessHandler(matcherToHandler);
}
@Test
public void onLogoutSuccessFirstMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
given(this.matcher.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler).onLogoutSuccess(this.request, this.response, this.authentication);
verifyNoMoreInteractions(this.matcher2, this.handler2, this.defaultHandler);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(boolean matchesReturn, HttpServletRequest request) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Test Case ID #spring-security_Test_118_2
Test Case Name: onLogoutSuccessSecondMatches(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\logout\DelegatingLogoutSuccessHandlerTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
- given(this.matcher2.matches(this.request)).willReturn(true);
+ this.matcher2 = createMockRequestMatcher(true, this.request);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler2).onLogoutSuccess(this.request, this.response, this.authentication);
verifyNoMoreInteractions(this.handler, this.defaultHandler);
Original Test Code (click to expand)
@BeforeEach
public void setup() {
LinkedHashMap<RequestMatcher, LogoutSuccessHandler> matcherToHandler = new LinkedHashMap<>();
matcherToHandler.put(this.matcher, this.handler);
matcherToHandler.put(this.matcher2, this.handler2);
this.delegatingHandler = new DelegatingLogoutSuccessHandler(matcherToHandler);
}
@Test
public void onLogoutSuccessSecondMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
given(this.matcher2.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler2).onLogoutSuccess(this.request, this.response, this.authentication);
verifyNoMoreInteractions(this.handler, this.defaultHandler);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(boolean matchesReturn, HttpServletRequest request) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Mock Clone Instance #spring-security_MCI_119
- Scope: method level
- Mocked Class:
org.springframework.security.web.util.matcher.RequestMatcher
- Test Case Count: 3
- MO Count: 4
Reusable Method
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mockRequestMatcher = mock(RequestMatcher.class);
given(mockRequestMatcher.matches(request)).willReturn(matchesReturn);
return mockRequestMatcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_119_1
Test Case Name: testDefaultEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstRM
Suggested Diff
@@
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
- RequestMatcher firstRM = mock(RequestMatcher.class);
- given(firstRM.matches(this.request)).willReturn(false);
+ RequestMatcher firstRM = createMockRequestMatcher(this.request, false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
@@
Original Test Code (click to expand)
@Test
public void testDefaultEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mockRequestMatcher = mock(RequestMatcher.class);
given(mockRequestMatcher.matches(request)).willReturn(matchesReturn);
return mockRequestMatcher;
}
Test Case ID #spring-security_Test_119_2
Test Case Name: testFirstEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstRM
Suggested Diff
@@
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
- RequestMatcher firstRM = mock(RequestMatcher.class);
+ RequestMatcher firstRM = createMockRequestMatcher(this.request, true);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
- given(firstRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(firstAEP).commence(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
verify(secondRM, never()).matches(this.request);
@@
Original Test Code (click to expand)
@Test
public void testFirstEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(firstAEP).commence(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
verify(secondRM, never()).matches(this.request);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mockRequestMatcher = mock(RequestMatcher.class);
given(mockRequestMatcher.matches(request)).willReturn(matchesReturn);
return mockRequestMatcher;
}
Test Case ID #spring-security_Test_119_3
Test Case Name: testSecondEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: firstRM
Suggested Diff
@@
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
- RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
+ RequestMatcher firstRM = createMockRequestMatcher(this.request, false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
@@
Original Test Code (click to expand)
@Test
public void testSecondEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mockRequestMatcher = mock(RequestMatcher.class);
given(mockRequestMatcher.matches(request)).willReturn(matchesReturn);
return mockRequestMatcher;
}
Test Case ID #spring-security_Test_119_4
Test Case Name: testSecondEntryPoint(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\DelegatingAuthenticationEntryPointTests.java)
Mock Object Variable Name: secondRM
Suggested Diff
@@
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
- RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
- given(secondRM.matches(this.request)).willReturn(true);
+ RequestMatcher secondRM = createMockRequestMatcher(this.request, true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
@@
Original Test Code (click to expand)
@Test
public void testSecondEntryPoint() throws Exception {
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher firstRM = mock(RequestMatcher.class);
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
RequestMatcher secondRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher mockRequestMatcher = mock(RequestMatcher.class);
given(mockRequestMatcher.matches(request)).willReturn(matchesReturn);
return mockRequestMatcher;
}
Mock Clone Instance #spring-security_MCI_120
- Scope: method level
- Mocked Class:
org.springframework.security.web.util.matcher.RequestMatcher
- Test Case Count: 3
- MO Count: 4
Reusable Method
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_120_1
Test Case Name: handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: matcher
Suggested Diff
@@
AccessDeniedHandler handler = mock(AccessDeniedHandler.class);
- RequestMatcher matcher = mock(RequestMatcher.class);
- given(matcher.matches(this.request)).willReturn(false);
+ RequestMatcher matcher = createMockRequestMatcher(this.request, false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(this.accessDeniedHandler).handle(this.request, null, null);
verify(handler, never()).handle(this.request, null, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() throws Exception {
AccessDeniedHandler handler = mock(AccessDeniedHandler.class);
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(this.request)).willReturn(false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(this.accessDeniedHandler).handle(this.request, null, null);
verify(handler, never()).handle(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Test Case ID #spring-security_Test_120_2
Test Case Name: handleWhenFirstMatchesThenOnlyFirstInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstMatcher
Suggested Diff
@@
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
- RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
- given(firstMatcher.matches(this.request)).willReturn(true);
+ RequestMatcher firstMatcher = createMockRequestMatcher(this.request, true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(firstHandler).handle(this.request, null, null);
verify(secondHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
verify(secondMatcher, never()).matches(this.request);
@@
Original Test Code (click to expand)
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() throws Exception {
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(firstHandler).handle(this.request, null, null);
verify(secondHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
verify(secondMatcher, never()).matches(this.request);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Test Case ID #spring-security_Test_120_3
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstMatcher
Suggested Diff
@@
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
- RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
+ RequestMatcher firstMatcher = createMockRequestMatcher(this.request, false);
given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
@@
- given(firstMatcher.matches(this.request)).willReturn(false);
+
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() throws Exception {
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(false);
given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Test Case ID #spring-security_Test_120_4
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\RequestMatcherDelegatingAccessDeniedHandlerTests.java)
Mock Object Variable Name: secondMatcher
Suggested Diff
@@
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
- RequestMatcher secondMatcher = mock(RequestMatcher.class);
+ RequestMatcher secondMatcher = createMockRequestMatcher(this.request, true);
given(firstMatcher.matches(this.request)).willReturn(false);
- given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
@@
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() throws Exception {
AccessDeniedHandler firstHandler = mock(AccessDeniedHandler.class);
RequestMatcher firstMatcher = mock(RequestMatcher.class);
AccessDeniedHandler secondHandler = mock(AccessDeniedHandler.class);
RequestMatcher secondMatcher = mock(RequestMatcher.class);
given(firstMatcher.matches(this.request)).willReturn(false);
given(secondMatcher.matches(this.request)).willReturn(true);
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
}
Reusable Method for MCI (click to expand)
private static RequestMatcher createMockRequestMatcher(HttpServletRequest request, boolean matchesReturn) {
RequestMatcher matcher = mock(RequestMatcher.class);
given(matcher.matches(request)).willReturn(matchesReturn);
return matcher;
}
Mock Clone Instance #spring-security_MCI_121
- Scope: method level
- Mocked Class:
org.springframework.security.web.firewall.FirewalledRequest
- Test Case Count: 2
- MO Count: 3
Reusable Method
private static FirewalledRequest createMockFirewalledRequest(String requestUri, String contextPath, MockHttpServletMapping httpServletMapping) {
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn(requestUri);
given(fwr.getContextPath()).willReturn(contextPath);
given(fwr.getHttpServletMapping()).willReturn(httpServletMapping);
return fwr;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_121_1
Test Case Name: wrapperIsResetWhenNoMatchingFilters(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: fwr
Suggested Diff
@@
HttpFirewall fw = mock(HttpFirewall.class);
- FirewalledRequest fwr = mock(FirewalledRequest.class);
- given(fwr.getRequestURI()).willReturn("/");
- given(fwr.getContextPath()).willReturn("");
- given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
+ FirewalledRequest fwr = createMockFirewalledRequest("/", "", TestMockHttpServletMappings.defaultMapping());
this.fcp.setFirewall(fw);
given(fw.getFirewalledRequest(this.request)).willReturn(fwr);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
@@
Original Test Code (click to expand)
@Test
public void wrapperIsResetWhenNoMatchingFilters() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
this.fcp.setFirewall(fw);
given(fw.getFirewalledRequest(this.request)).willReturn(fwr);
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
}
Reusable Method for MCI (click to expand)
private static FirewalledRequest createMockFirewalledRequest(String requestUri, String contextPath, MockHttpServletMapping httpServletMapping) {
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn(requestUri);
given(fwr.getContextPath()).willReturn(contextPath);
given(fwr.getHttpServletMapping()).willReturn(httpServletMapping);
return fwr;
}
Test Case ID #spring-security_Test_121_2
Test Case Name: bothWrappersAreResetWithNestedFcps(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: firstFwr
Suggested Diff
@@
this.fcp.setFirewall(fw);
- FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
- given(firstFwr.getRequestURI()).willReturn("/");
- given(firstFwr.getContextPath()).willReturn("");
- given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
+ FirewalledRequest firstFwr = createMockFirewalledRequest("/", "", TestMockHttpServletMappings.defaultMapping());
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
@@
Original Test Code (click to expand)
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, this.fcp));
firstFcp.setFirewall(fw);
this.fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
}
Reusable Method for MCI (click to expand)
private static FirewalledRequest createMockFirewalledRequest(String requestUri, String contextPath, MockHttpServletMapping httpServletMapping) {
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn(requestUri);
given(fwr.getContextPath()).willReturn(contextPath);
given(fwr.getHttpServletMapping()).willReturn(httpServletMapping);
return fwr;
}
Test Case ID #spring-security_Test_121_3
Test Case Name: bothWrappersAreResetWithNestedFcps(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: fwr
Suggested Diff
@@
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
- FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
- given(fwr.getRequestURI()).willReturn("/");
- given(fwr.getContextPath()).willReturn("");
- given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
+ FirewalledRequest fwr = createMockFirewalledRequest("/", "", TestMockHttpServletMappings.defaultMapping());
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
@@
Original Test Code (click to expand)
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, this.fcp));
firstFcp.setFirewall(fw);
this.fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
given(firstFwr.getRequestURI()).willReturn("/");
given(firstFwr.getContextPath()).willReturn("");
given(firstFwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
given(fwr.getRequestURI()).willReturn("/");
given(fwr.getContextPath()).willReturn("");
given(fwr.getHttpServletMapping()).willReturn(TestMockHttpServletMappings.defaultMapping());
given(fw.getFirewalledRequest(this.request)).willReturn(firstFwr);
given(fw.getFirewalledRequest(firstFwr)).willReturn(fwr);
given(fwr.getRequest()).willReturn(firstFwr);
given(firstFwr.getRequest()).willReturn(this.request);
given(this.matcher.matches(any())).willReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
}
Reusable Method for MCI (click to expand)
private static FirewalledRequest createMockFirewalledRequest(String requestUri, String contextPath, MockHttpServletMapping httpServletMapping) {
FirewalledRequest fwr = mock(FirewalledRequest.class);
given(fwr.getRequestURI()).willReturn(requestUri);
given(fwr.getContextPath()).willReturn(contextPath);
given(fwr.getHttpServletMapping()).willReturn(httpServletMapping);
return fwr;
}
Mock Clone Instance #spring-security_MCI_122
- Scope: method level
- Mocked Class:
org.springframework.security.web.webauthn.management.WebAuthnRelyingPartyOperations
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static WebAuthnRelyingPartyOperations createMockWebAuthnRelyingPartyOperations(PublicKeyCredentialCreationOptions options) {
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
return rpOperations;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_122_1
Mock Object Variable Name: rpOperations
Suggested Diff
@@
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
- WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
- ConfigCredentialCreationOptionsRepository.rpOperations = rpOperations;
- given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
+ WebAuthnRelyingPartyOperations rpOperations = createMockWebAuthnRelyingPartyOperations(options);
+ ConfigCredentialCreationOptionsRepository.rpOperations = rpOperations;
String attrName = "attrName";
HttpSessionPublicKeyCredentialCreationOptionsRepository creationOptionsRepository = new HttpSessionPublicKeyCredentialCreationOptionsRepository();
@@
Original Test Code (click to expand)
@Test
public void webauthnWhenConfiguredPublicKeyCredentialCreationOptionsRepository() throws Exception {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.setContext(new SecurityContextImpl(user));
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
ConfigCredentialCreationOptionsRepository.rpOperations = rpOperations;
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
String attrName = "attrName";
HttpSessionPublicKeyCredentialCreationOptionsRepository creationOptionsRepository = new HttpSessionPublicKeyCredentialCreationOptionsRepository();
creationOptionsRepository.setAttrName(attrName);
ConfigCredentialCreationOptionsRepository.creationOptionsRepository = creationOptionsRepository;
this.spring.register(ConfigCredentialCreationOptionsRepository.class).autowire();
this.mvc.perform(post("/webauthn/register/options")).andExpect(status().isOk()).andExpect(request().sessionAttribute(attrName, options));
}
Reusable Method for MCI (click to expand)
private static WebAuthnRelyingPartyOperations createMockWebAuthnRelyingPartyOperations(PublicKeyCredentialCreationOptions options) {
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
return rpOperations;
}
Test Case ID #spring-security_Test_122_2
Mock Object Variable Name: rpOperations
Suggested Diff
@@
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
- WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
+ WebAuthnRelyingPartyOperations rpOperations = createMockWebAuthnRelyingPartyOperations(options);
ConfigCredentialCreationOptionsRepositoryFromBean.rpOperations = rpOperations;
- given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
String attrName = "attrName";
HttpSessionPublicKeyCredentialCreationOptionsRepository creationOptionsRepository = new HttpSessionPublicKeyCredentialCreationOptionsRepository();
@@
Original Test Code (click to expand)
@Test
public void webauthnWhenConfiguredPublicKeyCredentialCreationOptionsRepositoryBeanPresent() throws Exception {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.setContext(new SecurityContextImpl(user));
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
ConfigCredentialCreationOptionsRepositoryFromBean.rpOperations = rpOperations;
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
String attrName = "attrName";
HttpSessionPublicKeyCredentialCreationOptionsRepository creationOptionsRepository = new HttpSessionPublicKeyCredentialCreationOptionsRepository();
creationOptionsRepository.setAttrName(attrName);
ConfigCredentialCreationOptionsRepositoryFromBean.creationOptionsRepository = creationOptionsRepository;
this.spring.register(ConfigCredentialCreationOptionsRepositoryFromBean.class).autowire();
this.mvc.perform(post("/webauthn/register/options")).andExpect(status().isOk()).andExpect(request().sessionAttribute(attrName, options));
}
Reusable Method for MCI (click to expand)
private static WebAuthnRelyingPartyOperations createMockWebAuthnRelyingPartyOperations(PublicKeyCredentialCreationOptions options) {
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
return rpOperations;
}
Test Case ID #spring-security_Test_122_3
Mock Object Variable Name: rpOperations
Suggested Diff
@@
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
- WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
- ConfigMessageConverter.rpOperations = rpOperations;
- given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
+ WebAuthnRelyingPartyOperations rpOperations = createMockWebAuthnRelyingPartyOperations(options);
+ ConfigMessageConverter.rpOperations = rpOperations;
HttpMessageConverter<Object> converter = mock(HttpMessageConverter.class);
given(converter.canWrite(any(), any())).willReturn(true);
String expectedBody = "123";
@@
Original Test Code (click to expand)
@Test
public void webauthnWhenConfiguredMessageConverter() throws Exception {
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password", "ROLE_USER");
SecurityContextHolder.setContext(new SecurityContextImpl(user));
PublicKeyCredentialCreationOptions options = TestPublicKeyCredentialCreationOptions.createPublicKeyCredentialCreationOptions().build();
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
ConfigMessageConverter.rpOperations = rpOperations;
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
HttpMessageConverter<Object> converter = mock(HttpMessageConverter.class);
given(converter.canWrite(any(), any())).willReturn(true);
String expectedBody = "123";
willAnswer((args) -> {
HttpOutputMessage out = (HttpOutputMessage) args.getArguments()[2];
out.getBody().write(expectedBody.getBytes(StandardCharsets.UTF_8));
return null;
}).given(converter).write(any(), any(), any());
ConfigMessageConverter.converter = converter;
this.spring.register(ConfigMessageConverter.class).autowire();
this.mvc.perform(post("/webauthn/register/options")).andExpect(status().isOk()).andExpect(content().string(expectedBody));
}
Reusable Method for MCI (click to expand)
private static WebAuthnRelyingPartyOperations createMockWebAuthnRelyingPartyOperations(PublicKeyCredentialCreationOptions options) {
WebAuthnRelyingPartyOperations rpOperations = mock(WebAuthnRelyingPartyOperations.class);
given(rpOperations.createPublicKeyCredentialCreationOptions(any())).willReturn(options);
return rpOperations;
}
Mock Clone Instance #spring-security_MCI_123
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 4
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2ClientCredentialsGrantRequest request, HttpHeaders headers) {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_123_1
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
- Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2ClientCredentialsGrantRequest request, HttpHeaders headers) {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_123_2
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
- Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2ClientCredentialsGrantRequest request, HttpHeaders headers) {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_123_3
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
- Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> addedHeadersConverter = MockConverter.createMockHeadersConverter(request, headers);
this.client.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.client.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2ClientCredentialsGrantRequest request, HttpHeaders headers) {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_123_4
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
ClientRegistration clientRegistration = request.getClientRegistration();
- Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
- given(headersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(request, headers);
this.client.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.client.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> createMockHeadersConverter(OAuth2ClientCredentialsGrantRequest request, HttpHeaders headers) {
Converter<OAuth2ClientCredentialsGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(request)).willReturn(headers);
return headersConverter;
}
}
Mock Clone Instance #spring-security_MCI_124
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 4
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, HttpHeaders headers) {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_124_1
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
- Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, HttpHeaders headers) {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_124_2
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
- Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, HttpHeaders headers) {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_124_3
Suggested Diff
@@
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
- Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(addedHeadersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> addedHeadersConverter = MockConverter.createMockConverter(request, headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, HttpHeaders headers) {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_124_4
Suggested Diff
@@
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
ClientRegistration clientRegistration = request.getClientRegistration();
- Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
- given(headersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockConverter(request, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
@@
Original Test Code (click to expand)
@Test
public void convertWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, HttpHeaders headers) {
Converter<OAuth2AuthorizationCodeGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_125
- Scope: method level
- Mocked Class:
java.security.Principal
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_125_1
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.configLocations(xml("JeeFilter")).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("joe");
+ Principal user = createMockPrincipal("joe");
// @formatter:off
MockHttpServletRequestBuilder rolesRequest = get("/roles").principal(user).with((request) -> {
request.addUserRole("admin");
request.addUserRole("user");
request.addUserRole("unmapped");
return request;
});
this.mvc.perform(rolesRequest).andExpect(content().string("ROLE_admin,ROLE_user"));
// @formatter:on
Original Test Code (click to expand)
@Test
public void loginWhenJeeFilterThenExtractsRoles() throws Exception {
this.spring.configLocations(xml("JeeFilter")).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
MockHttpServletRequestBuilder rolesRequest = get("/roles").principal(user).with((request) -> {
request.addUserRole("admin");
request.addUserRole("user");
request.addUserRole("unmapped");
return request;
});
this.mvc.perform(rolesRequest).andExpect(content().string("ROLE_admin,ROLE_user"));
}
Reusable Method for MCI (click to expand)
private static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
Test Case ID #spring-security_Test_125_2
Test Case Name: loginWhenJeeFilterCustomSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\http\MiscHttpConfigTests.java)
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.configLocations(xml("JeeFilterWithSecurityContextHolderStrategy")).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("joe");
+ Principal user = createMockPrincipal("joe");
// @formatter:off
MockHttpServletRequestBuilder rolesRequest = get("/roles").principal(user).with((request) -> {
request.addUserRole("admin");
request.addUserRole("user");
request.addUserRole("unmapped");
return request;
});
this.mvc.perform(rolesRequest).andExpect(content().string("ROLE_admin,ROLE_user"));
// @formatter:on
verify(this.spring.getContext().getBean(SecurityContextHolderStrategy.class), atLeastOnce()).getContext();
@@
Original Test Code (click to expand)
@Test
public void loginWhenJeeFilterCustomSecurityContextHolderStrategyThenUses() throws Exception {
this.spring.configLocations(xml("JeeFilterWithSecurityContextHolderStrategy")).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
MockHttpServletRequestBuilder rolesRequest = get("/roles").principal(user).with((request) -> {
request.addUserRole("admin");
request.addUserRole("user");
request.addUserRole("unmapped");
return request;
});
this.mvc.perform(rolesRequest).andExpect(content().string("ROLE_admin,ROLE_user"));
verify(this.spring.getContext().getBean(SecurityContextHolderStrategy.class), atLeastOnce()).getContext();
}
Reusable Method for MCI (click to expand)
private static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
Mock Clone Instance #spring-security_MCI_126
- Scope: class level
- Mocked Class:
java.security.Principal
- Test Case Count: 6
- MO Count: 6
Reusable Method
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_126_1
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("user");
+ Principal user = MockPrincipal.createMockPrincipal("user");
// @formatter:off
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
// @formatter:on
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
@@
Original Test Code (click to expand)
@Test
public void jeeWhenInvokedTwiceThenUsesOriginalMappableRoles() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Test Case ID #spring-security_Test_126_2
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(JeeMappableRolesConfig.class).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("user");
+ Principal user = MockPrincipal.createMockPrincipal("user");
// @formatter:off
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
// @formatter:on
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
Original Test Code (click to expand)
@Test
public void requestWhenJeeMappableRolesInLambdaThenAuthenticatedWithMappableRoles() throws Exception {
this.spring.register(JeeMappableRolesConfig.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Test Case ID #spring-security_Test_126_3
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(JeeMappableAuthoritiesConfig.class).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("user");
+ Principal user = MockPrincipal.createMockPrincipal("user");
// @formatter:off
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
Original Test Code (click to expand)
@Test
public void requestWhenJeeMappableAuthoritiesInLambdaThenAuthenticatedWithMappableAuthorities() throws Exception {
this.spring.register(JeeMappableAuthoritiesConfig.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
SecurityMockMvcResultMatchers.AuthenticatedMatcher authenticatedAsUser = authenticated().withAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER"));
this.mvc.perform(authRequest).andExpect(authenticatedAsUser);
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Test Case ID #spring-security_Test_126_4
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(JeeCustomAuthenticatedUserDetailsServiceConfig.class).autowire();
- Principal user = mock(Principal.class);
+ Principal user = MockPrincipal.createMockPrincipal("user");
User userDetails = new User("user", "N/A", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));
- given(user.getName()).willReturn("user");
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any())).willReturn(userDetails);
// @formatter:off
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
// @formatter:on
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
@@
Original Test Code (click to expand)
@Test
public void requestWhenCustomAuthenticatedUserDetailsServiceInLambdaThenCustomAuthenticatedUserDetailsServiceUsed() throws Exception {
this.spring.register(JeeCustomAuthenticatedUserDetailsServiceConfig.class).autowire();
Principal user = mock(Principal.class);
User userDetails = new User("user", "N/A", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(user.getName()).willReturn("user");
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any())).willReturn(userDetails);
MockHttpServletRequestBuilder authRequest = get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
return request;
});
this.mvc.perform(authRequest).andExpect(authenticated().withRoles("USER"));
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Test Case ID #spring-security_Test_126_5
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(JeeMappableRolesConfig.class, BaseController.class).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("joe");
+ Principal user = MockPrincipal.createMockPrincipal("joe");
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("ROLE_admin");
request.addUserRole("ROLE_user");
request.addUserRole("ROLE_unmapped");
return request;
})).andExpect(status().isOk()).andExpect(content().string("ROLE_admin,ROLE_user"));
@@
Original Test Code (click to expand)
@Test
public void requestWhenJeeUserThenBehaviorDiffersFromNamespaceForRoleNames() throws Exception {
this.spring.register(JeeMappableRolesConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("ROLE_admin");
request.addUserRole("ROLE_user");
request.addUserRole("ROLE_unmapped");
return request;
})).andExpect(status().isOk()).andExpect(content().string("ROLE_admin,ROLE_user"));
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Test Case ID #spring-security_Test_126_6
Mock Object Variable Name: user
Suggested Diff
@@
this.spring.register(JeeUserServiceRefConfig.class, BaseController.class).autowire();
- Principal user = mock(Principal.class);
- given(user.getName()).willReturn("joe");
+ Principal user = MockPrincipal.createMockPrincipal("joe");
User result = new User(user.getName(), "N/A", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_user"));
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
this.mvc.perform(get("/roles").principal(user)).andExpect(status().isOk()).andExpect(content().string("ROLE_user"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
@@
Original Test Code (click to expand)
@Test
public void requestWhenCustomAuthenticatedUserDetailsServiceThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(JeeUserServiceRefConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
User result = new User(user.getName(), "N/A", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_user"));
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
this.mvc.perform(get("/roles").principal(user)).andExpect(status().isOk()).andExpect(content().string("ROLE_user"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
}
Reusable Method for MCI (click to expand)
public class MockPrincipal {
public static Principal createMockPrincipal(String name) {
Principal user = mock(Principal.class);
given(user.getName()).willReturn(name);
return user;
}
}
Mock Clone Instance #spring-security_MCI_127
- Scope: method level
- Mocked Class:
org.springframework.security.core.context.SecurityContext
- Test Case Count: 3
- MO Count: 3
Reusable Method
private SecurityContext securityContext1;
@BeforeEach
public void setUp() {
securityContext1 = mock(SecurityContext.class);
}
securityContext1
The refactoring details in each test cases
Test Case ID #spring-security_Test_127_1
Test Case Name: loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext1
Suggested Diff
@@
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
- SecurityContext securityContext1 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext1`
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
Original Test Code (click to expand)
@Test
public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext1;
@BeforeEach
public void setUp() {
securityContext1 = mock(SecurityContext.class);
}
securityContext1
Test Case ID #spring-security_Test_127_2
Test Case Name: loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext1
Suggested Diff
@@
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
- SecurityContext securityContext1 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext1`
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
Original Test Code (click to expand)
@Test
public void loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext1;
@BeforeEach
public void setUp() {
securityContext1 = mock(SecurityContext.class);
}
securityContext1
Test Case ID #spring-security_Test_127_3
Test Case Name: loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext1
Suggested Diff
@@
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
- SecurityContext securityContext1 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext1`
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
Original Test Code (click to expand)
@Test
public void loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext1;
@BeforeEach
public void setUp() {
securityContext1 = mock(SecurityContext.class);
}
securityContext1
Mock Clone Instance #spring-security_MCI_128
- Scope: method level
- Mocked Class:
org.springframework.security.core.context.SecurityContext
- Test Case Count: 3
- MO Count: 3
Reusable Method
private SecurityContext securityContext2;
@BeforeEach
public void setUp() {
securityContext2 = mock(SecurityContext.class);
}
securityContext2;
The refactoring details in each test cases
Test Case ID #spring-security_Test_128_1
Test Case Name: loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext2
Suggested Diff
@@
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
- SecurityContext securityContext2 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext2`
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
- given(delegate2.loadContext(holder)).willReturn(securityContext2);
+ given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
- assertThat(returnedSecurityContext).isSameAs(securityContext2);
+ assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Original Test Code (click to expand)
@Test
public void loadContextWhenSecondDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(false);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext2;
@BeforeEach
public void setUp() {
securityContext2 = mock(SecurityContext.class);
}
securityContext2;
Test Case ID #spring-security_Test_128_2
Test Case Name: loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext2
Suggested Diff
@@
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
- SecurityContext securityContext2 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext2`
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
Original Test Code (click to expand)
@Test
public void loadContextWhenBothDelegateReturnsThenContextFromSecondDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(true);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext2);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext2;
@BeforeEach
public void setUp() {
securityContext2 = mock(SecurityContext.class);
}
securityContext2;
Test Case ID #spring-security_Test_128_3
Test Case Name: loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\DelegatingSecurityContextRepositoryTests.java)
Mock Object Variable Name: securityContext2
Suggested Diff
@@
SecurityContext securityContext1 = mock(SecurityContext.class);
- SecurityContext securityContext2 = mock(SecurityContext.class);
+ // removed local mock; replaced with global field `securityContext2`
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
- given(delegate2.loadContext(holder)).willReturn(securityContext2);
+ given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
Original Test Code (click to expand)
@Test
public void loadContextWhenFirstDelegateReturnsThenContextFromFirstDelegate() {
SecurityContextRepository delegate1 = mock(SecurityContextRepository.class);
SecurityContextRepository delegate2 = mock(SecurityContextRepository.class);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(this.request, this.response);
SecurityContext securityContext1 = mock(SecurityContext.class);
SecurityContext securityContext2 = mock(SecurityContext.class);
given(delegate1.loadContext(holder)).willReturn(securityContext1);
given(delegate1.containsContext(holder.getRequest())).willReturn(true);
given(delegate2.loadContext(holder)).willReturn(securityContext2);
given(delegate2.containsContext(holder.getRequest())).willReturn(false);
DelegatingSecurityContextRepository repository = new DelegatingSecurityContextRepository(delegate1, delegate2);
SecurityContext returnedSecurityContext = repository.loadContext(holder);
assertThat(returnedSecurityContext).isSameAs(securityContext1);
}
Reusable Method for MCI (click to expand)
private SecurityContext securityContext2;
@BeforeEach
public void setUp() {
securityContext2 = mock(SecurityContext.class);
}
securityContext2;
Mock Clone Instance #spring-security_MCI_129
- Scope: method level
- Mocked Class:
org.springframework.security.core.context.SecurityContext
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static SecurityContext createMockSecurityContext(Authentication authentication) {
SecurityContext securityContext = mock(SecurityContext.class);
given(securityContext.getAuthentication()).willReturn(authentication);
return securityContext;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_129_1
Test Case Name: logout(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: securityContext
Suggested Diff
@@
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
- SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
+ SecurityContext securityContext = createMockSecurityContext(token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
- given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
@@
Original Test Code (click to expand)
@Test
public void logout() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static SecurityContext createMockSecurityContext(Authentication authentication) {
SecurityContext securityContext = mock(SecurityContext.class);
given(securityContext.getAuthentication()).willReturn(authentication);
return securityContext;
}
Test Case ID #spring-security_Test_129_2
Test Case Name: logoutNullLoginContext(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: securityContext
Suggested Diff
@@
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
- SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
+ SecurityContext securityContext = createMockSecurityContext(token);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
- given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verifyNoMoreInteractions(event, securityContext, token);
@@
Original Test Code (click to expand)
@Test
public void logoutNullLoginContext() {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verifyNoMoreInteractions(event, securityContext, token);
}
Reusable Method for MCI (click to expand)
private static SecurityContext createMockSecurityContext(Authentication authentication) {
SecurityContext securityContext = mock(SecurityContext.class);
given(securityContext.getAuthentication()).willReturn(authentication);
return securityContext;
}
Test Case ID #spring-security_Test_129_3
Test Case Name: logoutLoginException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: securityContext
Suggested Diff
@@
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
- SecurityContext securityContext = mock(SecurityContext.class);
+ SecurityContext securityContext = createMockSecurityContext(token);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
- given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
@@
Original Test Code (click to expand)
@Test
public void logoutLoginException() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static SecurityContext createMockSecurityContext(Authentication authentication) {
SecurityContext securityContext = mock(SecurityContext.class);
given(securityContext.getAuthentication()).willReturn(authentication);
return securityContext;
}
Mock Clone Instance #spring-security_MCI_130
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.jwt.ReactiveRemoteJWKSource
- Test Case Count: 3
- MO Count: 3
Reusable Method
private ReactiveRemoteJWKSource jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(ReactiveRemoteJWKSource.class);
}
jwkSource;
The refactoring details in each test cases
Test Case ID #spring-security_Test_130_1
Test Case Name: jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
- ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
Reusable Method for MCI (click to expand)
private ReactiveRemoteJWKSource jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(ReactiveRemoteJWKSource.class);
}
jwkSource;
Test Case ID #spring-security_Test_130_2
Test Case Name: jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
- ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Reusable Method for MCI (click to expand)
private ReactiveRemoteJWKSource jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(ReactiveRemoteJWKSource.class);
}
jwkSource;
Test Case ID #spring-security_Test_130_3
Test Case Name: jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwkSource
Suggested Diff
@@
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
- ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
+ // removed local mock; replaced with global field `jwkSource`
// @formatter:off
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource).block();
// @formatter:on
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Original Test Code (click to expand)
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector).isInstanceOf(JWSVerificationKeySelector.class);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
Reusable Method for MCI (click to expand)
private ReactiveRemoteJWKSource jwkSource;
@BeforeEach
public void setUp() {
jwkSource = mock(ReactiveRemoteJWKSource.class);
}
jwkSource;
Mock Clone Instance #spring-security_MCI_131
- Scope: method level
- Mocked Class:
org.springframework.security.core.session.ReactiveSessionInformation
- Test Case Count: 3
- MO Count: 7
Reusable Method
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_131_1
Test Case Name: handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session1
Suggested Diff
@@
void handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions() {
- ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
+ ReactiveSessionInformation session1 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760010L), "session1");
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
- given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
- given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session2.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 2, createWebSession());
this.handler.handle(context).block();
verify(session2).invalidate();
// used by comparator to sort the sessions
verify(session1).getLastAccessTime();
// used by comparator to sort the sessions
verify(session2).getLastAccessTime();
verify(session1).getSessionId();
// used to invalidate session against
verify(session2, times(2)).getSessionId();
// the
// WebSessionStore
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
Original Test Code (click to expand)
@Test
void handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session2.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 2, createWebSession());
this.handler.handle(context).block();
verify(session2).invalidate();
verify(session1).getLastAccessTime();
verify(session2).getLastAccessTime();
verify(session1).getSessionId();
verify(session2, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_2
Test Case Name: handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session2
Suggested Diff
@@
void handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
- ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
- given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
- given(session1.getSessionId()).willReturn("session1");
- given(session2.getSessionId()).willReturn("session2");
+ given(session1.getSessionId()).willReturn("session1");
+ ReactiveSessionInformation session2 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760000L), "session2");
given(session2.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 2, createWebSession());
this.handler.handle(context).block();
verify(session2).invalidate();
// used by comparator to sort the sessions
verify(session1).getLastAccessTime();
// used by comparator to sort the sessions
verify(session2).getLastAccessTime();
verify(session1).getSessionId();
// used to invalidate session against
verify(session2, times(2)).getSessionId();
// the
// WebSessionStore
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
@@
Original Test Code (click to expand)
@Test
void handleWhenInvokedThenInvalidatesLeastRecentlyUsedSessions() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session2.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 2, createWebSession());
this.handler.handle(context).block();
verify(session2).invalidate();
verify(session1).getLastAccessTime();
verify(session2).getLastAccessTime();
verify(session1).getSessionId();
verify(session2, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_3
Test Case Name: handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session1
Suggested Diff
@@
- ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
+ ReactiveSessionInformation session1 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760010L), "session1");
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
- given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
- given(session1.invalidate()).willReturn(Mono.empty());
given(session2.invalidate()).willReturn(Mono.empty());
- given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
// @formatter:off
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
// used by comparator to sort the sessions
verify(session1, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session2, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
// @formatter:on
@@
Original Test Code (click to expand)
@Test
void handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
given(session1.invalidate()).willReturn(Mono.empty());
given(session2.invalidate()).willReturn(Mono.empty());
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
verify(session1, atLeastOnce()).getLastAccessTime();
verify(session2, atLeastOnce()).getLastAccessTime();
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_4
Test Case Name: handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session2
Suggested Diff
@@
void handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
- ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
+ ReactiveSessionInformation session2 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760020L), "session2");
given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
given(session1.invalidate()).willReturn(Mono.empty());
- given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
given(session3.invalidate()).willReturn(Mono.empty());
given(session1.getSessionId()).willReturn("session1");
- given(session2.invalidate()).willReturn(Mono.empty());
given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
// @formatter:off
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
// used by comparator to sort the sessions
verify(session1, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session2, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
// @formatter:on
}
@@
Original Test Code (click to expand)
@Test
void handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
given(session1.invalidate()).willReturn(Mono.empty());
given(session2.invalidate()).willReturn(Mono.empty());
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
verify(session1, atLeastOnce()).getLastAccessTime();
verify(session2, atLeastOnce()).getLastAccessTime();
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_5
Test Case Name: handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session3
Suggested Diff
@@
void handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
- ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
- given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
- given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
- given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
+ ReactiveSessionInformation session3 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760030L), "session3");
given(session1.invalidate()).willReturn(Mono.empty());
given(session2.invalidate()).willReturn(Mono.empty());
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
- given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
// @formatter:off
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
// used by comparator to sort the sessions
verify(session1, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session2, atLeastOnce()).getLastAccessTime();
// used by comparator to sort the sessions
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
// @formatter:on
}
@@
Original Test Code (click to expand)
@Test
void handleWhenMoreThanOneSessionToInvalidateThenInvalidatesAllOfThem() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session3 = mock(ReactiveSessionInformation.class);
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760020L));
given(session3.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760030L));
given(session1.invalidate()).willReturn(Mono.empty());
given(session2.invalidate()).willReturn(Mono.empty());
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn("session2");
given(session3.getSessionId()).willReturn("session3");
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2, session3), 2, createWebSession());
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).invalidate();
verify(session1, times(2)).getSessionId();
verify(session2, times(2)).getSessionId();
verify(session3).getSessionId();
verify(session1, atLeastOnce()).getLastAccessTime();
verify(session2, atLeastOnce()).getLastAccessTime();
verify(session3, atLeastOnce()).getLastAccessTime();
verify(this.webSessionStore).removeSession("session1");
verify(this.webSessionStore).removeSession("session2");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session1);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session3);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_6
Test Case Name: handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session1
Suggested Diff
@@
void handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession() {
- ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
+ ReactiveSessionInformation session1 = createMockReactiveSessionInformation(
+ Instant.ofEpochMilli(1700827760010L),
+ "session1");
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
MockWebSession currentSession = createWebSession();
- given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
- given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn(currentSession.getId());
- given(session1.invalidate()).willReturn(Mono.empty());
+ given(session1.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 1, currentSession);
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).getSessionId();
verify(session1, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session1");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
@@
Original Test Code (click to expand)
@Test
void handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
MockWebSession currentSession = createWebSession();
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn(currentSession.getId());
given(session1.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 1, currentSession);
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).getSessionId();
verify(session1, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session1");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Test Case ID #spring-security_Test_131_7
Test Case Name: handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authentication\session\InvalidateLeastUsedServerMaximumSessionsExceededHandlerTests.java)
Mock Object Variable Name: session2
Suggested Diff
@@
void handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
- ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
MockWebSession currentSession = createWebSession();
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
- given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
- given(session1.getSessionId()).willReturn("session1");
- given(session2.getSessionId()).willReturn(currentSession.getId());
+ ReactiveSessionInformation session2 = createMockReactiveSessionInformation(Instant.ofEpochMilli(1700827760000L), currentSession.getId());
given(session1.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 1, currentSession);
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).getSessionId();
verify(session1, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session1");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
@@
Original Test Code (click to expand)
@Test
void handleWhenCurrentSessionIsRegisteredThenDoNotInvalidateCurrentSession() {
ReactiveSessionInformation session1 = mock(ReactiveSessionInformation.class);
ReactiveSessionInformation session2 = mock(ReactiveSessionInformation.class);
MockWebSession currentSession = createWebSession();
given(session1.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760010L));
given(session2.getLastAccessTime()).willReturn(Instant.ofEpochMilli(1700827760000L));
given(session1.getSessionId()).willReturn("session1");
given(session2.getSessionId()).willReturn(currentSession.getId());
given(session1.invalidate()).willReturn(Mono.empty());
MaximumSessionsContext context = new MaximumSessionsContext(mock(Authentication.class), List.of(session1, session2), 1, currentSession);
this.handler.handle(context).block();
verify(session1).invalidate();
verify(session2).getSessionId();
verify(session1, times(2)).getSessionId();
verify(this.webSessionStore).removeSession("session1");
verifyNoMoreInteractions(this.webSessionStore);
verifyNoMoreInteractions(session2);
verifyNoMoreInteractions(session1);
}
Reusable Method for MCI (click to expand)
private static ReactiveSessionInformation createMockReactiveSessionInformation(Instant lastAccessTime, String sessionId) {
ReactiveSessionInformation mockSession = mock(ReactiveSessionInformation.class);
given(mockSession.getLastAccessTime()).willReturn(lastAccessTime);
given(mockSession.getSessionId()).willReturn(sessionId);
return mockSession;
}
Mock Clone Instance #spring-security_MCI_132
- Scope: method level
- Mocked Class:
org.springframework.security.web.authentication.logout.LogoutHandler
- Test Case Count: 3
- MO Count: 3
Reusable Method
private LogoutHandler securityContextLogoutHandler;
@BeforeEach
public void setUp() {
securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
}
securityContextLogoutHandler
The refactoring details in each test cases
Test Case ID #spring-security_Test_132_1
Test Case Name: callLogoutHandlersSuccessfullyWithArray(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\logout\CompositeLogoutHandlerTests.java)
Mock Object Variable Name: securityContextLogoutHandler
Suggested Diff
@@
@Test
public void callLogoutHandlersSuccessfullyWithArray() {
- LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
+ // removed local mock; replaced with global field `securityContextLogoutHandler`
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler handler = new CompositeLogoutHandler(securityContextLogoutHandler, csrfLogoutHandler);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
- verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
+ verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Original Test Code (click to expand)
@Test
public void callLogoutHandlersSuccessfullyWithArray() {
LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler handler = new CompositeLogoutHandler(securityContextLogoutHandler, csrfLogoutHandler);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Reusable Method for MCI (click to expand)
private LogoutHandler securityContextLogoutHandler;
@BeforeEach
public void setUp() {
securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
}
securityContextLogoutHandler
Test Case ID #spring-security_Test_132_2
Test Case Name: callLogoutHandlersSuccessfully(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\logout\CompositeLogoutHandlerTests.java)
Mock Object Variable Name: securityContextLogoutHandler
Suggested Diff
@@
@Test
public void callLogoutHandlersSuccessfully() {
- LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
+ // removed local mock; replaced with global field `securityContextLogoutHandler`
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
List<LogoutHandler> logoutHandlers = Arrays.asList(securityContextLogoutHandler, csrfLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
- verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
+ verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Original Test Code (click to expand)
@Test
public void callLogoutHandlersSuccessfully() {
LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
List<LogoutHandler> logoutHandlers = Arrays.asList(securityContextLogoutHandler, csrfLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Reusable Method for MCI (click to expand)
private LogoutHandler securityContextLogoutHandler;
@BeforeEach
public void setUp() {
securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
}
securityContextLogoutHandler
Test Case ID #spring-security_Test_132_3
Test Case Name: callLogoutHandlersThrowException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\logout\CompositeLogoutHandlerTests.java)
Mock Object Variable Name: secondLogoutHandler
Suggested Diff
@@
@Test
public void callLogoutHandlersThrowException() {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
- LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
+ // removed local mock; replaced with global field `securityContextLogoutHandler`
willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
- List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
+ List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, securityContextLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)));
- InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
+ InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, securityContextLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
- logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
+ logoutHandlersInOrder.verify(securityContextLogoutHandler, never()).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Original Test Code (click to expand)
@Test
public void callLogoutHandlersThrowException() {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)));
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
Reusable Method for MCI (click to expand)
private LogoutHandler securityContextLogoutHandler;
@BeforeEach
public void setUp() {
securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
}
securityContextLogoutHandler
Mock Clone Instance #spring-security_MCI_133
- Scope: method level
- Mocked Class:
org.springframework.security.access.intercept.RunAsManager
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_133_1
Test Case Name: runAsReplacementIsCorrectlySet(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\intercept\aopalliance\MethodSecurityInterceptorTests.java)
Mock Object Variable Name: runAs
Suggested Diff
@@
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
- final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
+ final RunAsManager runAs = createMockRunAsManager(this.token, runAsToken);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
- given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
String result = this.advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@@
Original Test Code (click to expand)
@Test
public void runAsReplacementIsCorrectlySet() {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
String result = this.advisedTarget.makeUpperCase("hello");
assertThat(result).isEqualTo("HELLO org.springframework.security.access.intercept.RunAsUserToken true");
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
Reusable Method for MCI (click to expand)
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
Test Case ID #spring-security_Test_133_2
Test Case Name: runAsReplacementCleansAfterException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\intercept\aopalliance\MethodSecurityInterceptorTests.java)
Mock Object Variable Name: runAs
Suggested Diff
@@
this.token.setAuthenticated(true);
- final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
+ final RunAsManager runAs = createMockRunAsManager(this.token, runAsToken);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
- given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@@
Original Test Code (click to expand)
@Test
public void runAsReplacementCleansAfterException() {
createTarget(true);
given(this.realTarget.makeUpperCase(anyString())).willThrow(new RuntimeException());
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole();
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
Reusable Method for MCI (click to expand)
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
Mock Clone Instance #spring-security_MCI_134
- Scope: method level
- Mocked Class:
org.springframework.security.access.intercept.RunAsManager
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_134_1
Test Case Name: invokeWithAspectJCallbackRunAsReplacementCleansAfterException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\intercept\aspectj\AspectJMethodSecurityInterceptorTests.java)
Mock Object Variable Name: runAs
Suggested Diff
@@
this.token.setAuthenticated(true);
- final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
+ final RunAsManager runAs = createMockRunAsManager(this.token, runAsToken);
this.interceptor.setRunAsManager(runAs);
- given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@@
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void invokeWithAspectJCallbackRunAsReplacementCleansAfterException() {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
Reusable Method for MCI (click to expand)
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
Test Case ID #spring-security_Test_134_2
Test Case Name: invokeRunAsReplacementCleansAfterException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\access\intercept\aspectj\AspectJMethodSecurityInterceptorTests.java)
Mock Object Variable Name: runAs
Suggested Diff
@@
this.token.setAuthenticated(true);
- final RunAsManager runAs = mock(RunAsManager.class);
- final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
- this.interceptor.setRunAsManager(runAs);
- given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
+ final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
+ final RunAsManager runAs = createMockRunAsManager(this.token, runAsToken);
+ this.interceptor.setRunAsManager(runAs);
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint));
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@@
Original Test Code (click to expand)
@Test
@SuppressWarnings("unchecked")
public void invokeRunAsReplacementCleansAfterException() throws Throwable {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.token);
this.token.setAuthenticated(true);
final RunAsManager runAs = mock(RunAsManager.class);
final RunAsUserToken runAsToken = new RunAsUserToken("key", "someone", "creds", this.token.getAuthorities(), TestingAuthenticationToken.class);
this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.joinPoint.proceed()).willThrow(new RuntimeException());
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint));
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
}
Reusable Method for MCI (click to expand)
private static RunAsManager createMockRunAsManager(Authentication token, RunAsUserToken runAsToken) {
RunAsManager runAs = mock(RunAsManager.class);
given(runAs.buildRunAs(eq(token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
return runAs;
}
Mock Clone Instance #spring-security_MCI_135
- Scope: class level
- Mocked Class:
org.opensaml.saml.common.assertion.ValidationContext
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockValidationContext {
public static ValidationContext createMockValidationContext(Map<String, Object> staticParameters) {
ValidationContext context = mock(ValidationContext.class);
given(context.getStaticParameters()).willReturn(staticParameters);
return context;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_135_1
Test Case Name: authenticateWhenValidationContextCustomizedThenUsers(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml4Test\java\org\springframework\security\saml2\provider\service\authentication\OpenSaml4AuthenticationProviderTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton("blah"));
- ValidationContext context = mock(ValidationContext.class);
- given(context.getStaticParameters()).willReturn(parameters);
+ ValidationContext context = MockValidationContext.createMockValidationContext(parameters);
OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
provider.setAssertionValidator(OpenSaml4AuthenticationProvider.createDefaultAssertionValidator((assertionToken) -> context));
Response response = response();
Assertion assertion = assertion();
response.getAssertions().add(signed(assertion));
Saml2AuthenticationToken token = token(response, verifying(registration()));
// @formatter:off
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class).satisfies((error) -> assertThat(error).hasMessageContaining("Invalid assertion"));
// @formatter:on
verify(context, atLeastOnce()).getStaticParameters();
}
Original Test Code (click to expand)
@Test
public void authenticateWhenValidationContextCustomizedThenUsers() {
Map<String, Object> parameters = new HashMap<>();
parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton("blah"));
ValidationContext context = mock(ValidationContext.class);
given(context.getStaticParameters()).willReturn(parameters);
OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider();
provider.setAssertionValidator(OpenSaml4AuthenticationProvider.createDefaultAssertionValidator((assertionToken) -> context));
Response response = response();
Assertion assertion = assertion();
response.getAssertions().add(signed(assertion));
Saml2AuthenticationToken token = token(response, verifying(registration()));
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class).satisfies((error) -> assertThat(error).hasMessageContaining("Invalid assertion"));
verify(context, atLeastOnce()).getStaticParameters();
}
Reusable Method for MCI (click to expand)
public class MockValidationContext {
public static ValidationContext createMockValidationContext(Map<String, Object> staticParameters) {
ValidationContext context = mock(ValidationContext.class);
given(context.getStaticParameters()).willReturn(staticParameters);
return context;
}
}
Test Case ID #spring-security_Test_135_2
Test Case Name: authenticateWhenValidationContextCustomizedThenUsers(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\authentication\OpenSaml5AuthenticationProviderTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton("blah"));
- ValidationContext context = mock(ValidationContext.class);
- given(context.getStaticParameters()).willReturn(parameters);
+ ValidationContext context = MockValidationContext.createMockValidationContext(parameters);
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setAssertionValidator(OpenSaml5AuthenticationProvider.createDefaultAssertionValidator((assertionToken) -> context));
Response response = response();
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenValidationContextCustomizedThenUsers() {
Map<String, Object> parameters = new HashMap<>();
parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton("blah"));
ValidationContext context = mock(ValidationContext.class);
given(context.getStaticParameters()).willReturn(parameters);
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setAssertionValidator(OpenSaml5AuthenticationProvider.createDefaultAssertionValidator((assertionToken) -> context));
Response response = response();
Assertion assertion = assertion();
response.getAssertions().add(signed(assertion));
Saml2AuthenticationToken token = token(response, verifying(registration()));
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class).satisfies((error) -> assertThat(error).hasMessageContaining("Invalid assertion"));
verify(context, atLeastOnce()).getStaticParameters();
}
Reusable Method for MCI (click to expand)
public class MockValidationContext {
public static ValidationContext createMockValidationContext(Map<String, Object> staticParameters) {
ValidationContext context = mock(ValidationContext.class);
given(context.getStaticParameters()).willReturn(staticParameters);
return context;
}
}
Mock Clone Instance #spring-security_MCI_136
- Scope: method level
- Mocked Class:
jakarta.servlet.ServletContext
- Test Case Count: 13
- MO Count: 13
Reusable Method
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_136_1
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_2
Test Case Name: onStartupWhenConfigurationClassThenAddsContextLoaderListener(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(any(ContextLoaderListener.class));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(any(ContextLoaderListener.class));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_3
Test Case Name: onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(HttpSessionEventPublisher.class.getName());
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(HttpSessionEventPublisher.class.getName());
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_4
Test Case Name: onStartupWhenCustomSecurityDispatcherTypesThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void onStartupWhenCustomSecurityDispatcherTypesThenUses() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenCustomSecurityDispatcherTypesThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_5
Test Case Name: onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected String getDispatcherWebApplicationContextSuffix() {
return "dispatcher";
}
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute()).isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected String getDispatcherWebApplicationContextSuffix() {
return "dispatcher";
}
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute()).isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_6
Test Case Name: onStartupWhenInsertFiltersThenInserted(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
- ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
+ FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context).addFilter(anyString(), eq(filter1));
verify(context).addFilter(anyString(), eq(filter2));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenInsertFiltersThenInserted() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context).addFilter(anyString(), eq(filter1));
verify(context).addFilter(anyString(), eq(filter2));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_7
Test Case Name: onStartupWhenDuplicateFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter1 = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterInsertedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_8
Test Case Name: onStartupWhenInsertFiltersEmptyThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
public void onStartupWhenInsertFiltersEmptyThenException() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Original Test Code (click to expand)
@Test
public void onStartupWhenInsertFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_9
Test Case Name: onStartupWhenNullFilterInsertedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
- FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
- ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
+ FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
+ ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterInsertedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_10
Test Case Name: onStartupWhenAppendFiltersThenAppended(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context, times(3)).addFilter(anyString(), any(Filter.class));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenAppendFiltersThenAppended() {
Filter filter1 = mock(Filter.class);
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
verify(context, times(3)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_11
Test Case Name: onStartupWhenDuplicateFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter1 = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenDuplicateFilterAppendedThenException() {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage("Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_12
Test Case Name: onStartupWhenAppendFiltersEmptyThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void onStartupWhenAppendFiltersEmptyThenException() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Original Test Code (click to expand)
@Test
public void onStartupWhenAppendFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context)).withMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_136_13
Test Case Name: onStartupWhenNullFilterAppendedThenException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
Filter filter = mock(Filter.class);
- ServletContext context = mock(ServletContext.class);
+ ServletContext context = createMockServletContext(registration, proxyCaptor);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
- given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
@@
Original Test Code (click to expand)
@Test
public void onStartupWhenNullFilterAppendedThenException() {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatIllegalArgumentException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).withMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration, ArgumentCaptor<DelegatingFilterProxy> proxyCaptor) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
return context;
}
Mock Clone Instance #spring-security_MCI_137
- Scope: method level
- Mocked Class:
jakarta.servlet.ServletContext
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
return context;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_137_1
Test Case Name: onStartupWhenDefaultsThenSessionTrackingModes(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
public void onStartupWhenDefaultsThenSessionTrackingModes() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenDefaultsThenSessionTrackingModes() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
return context;
}
Test Case ID #spring-security_Test_137_2
Test Case Name: onStartupWhenSessionTrackingModesConfiguredThenUsed(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\AbstractSecurityWebApplicationInitializerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
public void onStartupWhenSessionTrackingModesConfiguredThenUsed() {
- ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
+ ServletContext context = createMockServletContext(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
- given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
willDoNothing().given(context).setSessionTrackingModes(any());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);
}
Original Test Code (click to expand)
@Test
public void onStartupWhenSessionTrackingModesConfiguredThenUsed() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
@SuppressWarnings("unchecked")
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor.forClass(Set.class);
willDoNothing().given(context).setSessionTrackingModes(any());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
verify(context).addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture());
assertProxyDefaults(proxyCaptor.getValue());
verify(context).setSessionTrackingModes(modesCaptor.capture());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);
}
Reusable Method for MCI (click to expand)
private static ServletContext createMockServletContext(FilterRegistration.Dynamic registration) {
ServletContext context = mock(ServletContext.class);
given(context.addFilter(eq("springSecurityFilterChain"), any(DelegatingFilterProxy.class))).willReturn(registration);
return context;
}
Mock Clone Instance #spring-security_MCI_138
- Scope: class level
- Mocked Class:
org.springframework.security.oauth2.core.OAuth2TokenValidator<org.springframework.security.oauth2.jwt.Jwt>
- Test Case Count: 3
- MO Count: 4
Reusable Method
public class MockOAuth2TokenValidator {
public static OAuth2TokenValidator<Jwt> createMockJwtValidator(OAuth2TokenValidatorResult result) {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
return jwtValidator;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_138_1
Test Case Name: decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwtValidator
Suggested Diff
@@
OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
- OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
- given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure));
+ OAuth2TokenValidator<Jwt> jwtValidator = MockOAuth2TokenValidator.createMockJwtValidator(OAuth2TokenValidatorResult.failure(failure));
this.jwtDecoder.setJwtValidator(jwtValidator);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() {
OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure));
this.jwtDecoder.setJwtValidator(jwtValidator);
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
}
Reusable Method for MCI (click to expand)
public class MockOAuth2TokenValidator {
public static OAuth2TokenValidator<Jwt> createMockJwtValidator(OAuth2TokenValidatorResult result) {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
return jwtValidator;
}
}
Test Case ID #spring-security_Test_138_2
Test Case Name: decodeWhenJwtValidationHasTwoErrorsThenJwtExceptionMessageShowsFirstError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwtValidator
Suggested Diff
@@
OAuth2Error firstFailure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error secondFailure = new OAuth2Error("another-error", "another-description", "another-uri");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(firstFailure, secondFailure);
- OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
- given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
+ OAuth2TokenValidator<Jwt> jwtValidator = MockOAuth2TokenValidator.createMockJwtValidator(result);
this.jwtDecoder.setJwtValidator(jwtValidator);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description").satisfies((ex) -> assertThat(ex).hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure)));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void decodeWhenJwtValidationHasTwoErrorsThenJwtExceptionMessageShowsFirstError() {
OAuth2Error firstFailure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error secondFailure = new OAuth2Error("another-error", "another-description", "another-uri");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(firstFailure, secondFailure);
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
this.jwtDecoder.setJwtValidator(jwtValidator);
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description").satisfies((ex) -> assertThat(ex).hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure)));
}
Reusable Method for MCI (click to expand)
public class MockOAuth2TokenValidator {
public static OAuth2TokenValidator<Jwt> createMockJwtValidator(OAuth2TokenValidatorResult result) {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
return jwtValidator;
}
}
Test Case ID #spring-security_Test_138_3
Test Case Name: decodeWhenReadingErrorPickTheFirstErrorMessage(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusJwtDecoderTests.java)
Mock Object Variable Name: jwtValidator
Suggested Diff
@@
@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
- OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
+ OAuth2TokenValidator<Jwt> jwtValidator = MockOAuth2TokenValidator.createMockJwtValidator(result);
this.jwtDecoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
- given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
this.jwtDecoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT)).withMessageContaining("mock-description");
}
Reusable Method for MCI (click to expand)
public class MockOAuth2TokenValidator {
public static OAuth2TokenValidator<Jwt> createMockJwtValidator(OAuth2TokenValidatorResult result) {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
return jwtValidator;
}
}
Test Case ID #spring-security_Test_138_4
Test Case Name: decodeWhenReadingErrorPickTheFirstErrorMessage(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoderTests.java)
Mock Object Variable Name: jwtValidator
Suggested Diff
@@
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
- OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
+ OAuth2TokenValidator<Jwt> jwtValidator = MockOAuth2TokenValidator.createMockJwtValidator(result);
this.decoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
- given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()).withMessageContaining("mock-description");
// @formatter:on
}
Original Test Code (click to expand)
@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
this.decoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
assertThatExceptionOfType(JwtValidationException.class).isThrownBy(() -> this.decoder.decode(this.messageReadToken).block()).withMessageContaining("mock-description");
}
Reusable Method for MCI (click to expand)
public class MockOAuth2TokenValidator {
public static OAuth2TokenValidator<Jwt> createMockJwtValidator(OAuth2TokenValidatorResult result) {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
return jwtValidator;
}
}
Mock Clone Instance #spring-security_MCI_139
- Scope: class level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 2
- MO Count: 2
Reusable Method
public class MockAuthentication {
public static Authentication createMockAuthentication(boolean isAuthenticated) {
Authentication authentication = Mockito.mock(Authentication.class);
Mockito.when(authentication.isAuthenticated()).thenReturn(isAuthenticated);
return authentication;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_139_1
Test Case Name: checkWhenAuthenticatedThenReturnTrue(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\AuthenticatedReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
- given(this.authentication.isAuthenticated()).willReturn(true);
+ this.authentication = MockAuthentication.createMockAuthentication(true);
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
Original Test Code (click to expand)
@Test
public void checkWhenAuthenticatedThenReturnTrue() {
given(this.authentication.isAuthenticated()).willReturn(true);
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockAuthentication {
public static Authentication createMockAuthentication(boolean isAuthenticated) {
Authentication authentication = Mockito.mock(Authentication.class);
Mockito.when(authentication.isAuthenticated()).thenReturn(isAuthenticated);
return authentication;
}
}
Test Case ID #spring-security_Test_139_2
Test Case Name: checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\AuthorityReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
- given(this.authentication.isAuthenticated()).willReturn(true);
- given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
+ this.authentication = MockAuthentication.createMockAuthentication(true);
+ given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
Original Test Code (click to expand)
@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
given(this.authentication.isAuthenticated()).willReturn(true);
given(this.authentication.getAuthorities()).willReturn(Collections.emptyList());
boolean granted = this.manager.check(Mono.just(this.authentication), null).block().isGranted();
assertThat(granted).isFalse();
}
Reusable Method for MCI (click to expand)
public class MockAuthentication {
public static Authentication createMockAuthentication(boolean isAuthenticated) {
Authentication authentication = Mockito.mock(Authentication.class);
Mockito.when(authentication.isAuthenticated()).thenReturn(isAuthenticated);
return authentication;
}
}
Mock Clone Instance #spring-security_MCI_140
- Scope: method level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static Authentication createMockAuthentication(String principalName) {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(principalName);
return authentication;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_140_1
Test Case Name: loadAuthorizedClientWhenClientRegistrationFoundAndAssociatedToPrincipalThenReturnAuthorizedClient(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\InMemoryOAuth2AuthorizedClientServiceTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
public void loadAuthorizedClientWhenClientRegistrationFoundAndAssociatedToPrincipalThenReturnAuthorizedClient() {
- Authentication authentication = mock(Authentication.class);
- given(authentication.getName()).willReturn(this.principalName1);
+ Authentication authentication = createMockAuthentication(this.principalName1);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(loadedAuthorizedClient).satisfies(isEqualTo(authorizedClient));
}
Original Test Code (click to expand)
@Test
public void loadAuthorizedClientWhenClientRegistrationFoundAndAssociatedToPrincipalThenReturnAuthorizedClient() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName1);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(loadedAuthorizedClient).satisfies(isEqualTo(authorizedClient));
}
Reusable Method for MCI (click to expand)
private static Authentication createMockAuthentication(String principalName) {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(principalName);
return authentication;
}
Test Case ID #spring-security_Test_140_2
Test Case Name: saveAuthorizedClientWhenSavedThenCanLoad(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\InMemoryOAuth2AuthorizedClientServiceTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
public void saveAuthorizedClientWhenSavedThenCanLoad() {
- Authentication authentication = mock(Authentication.class);
- given(authentication.getName()).willReturn(this.principalName2);
+ Authentication authentication = createMockAuthentication(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration3, this.principalName2, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration3.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).satisfies(isEqualTo(authorizedClient));
}
Original Test Code (click to expand)
@Test
public void saveAuthorizedClientWhenSavedThenCanLoad() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration3, this.principalName2, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration3.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).satisfies(isEqualTo(authorizedClient));
}
Reusable Method for MCI (click to expand)
private static Authentication createMockAuthentication(String principalName) {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(principalName);
return authentication;
}
Test Case ID #spring-security_Test_140_3
Test Case Name: removeAuthorizedClientWhenSavedThenRemoved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\InMemoryOAuth2AuthorizedClientServiceTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
public void removeAuthorizedClientWhenSavedThenRemoved() {
- Authentication authentication = mock(Authentication.class);
- given(authentication.getName()).willReturn(this.principalName2);
+ Authentication authentication = createMockAuthentication(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName2, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNotNull();
this.authorizedClientService.removeAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNull();
}
Original Test Code (click to expand)
@Test
public void removeAuthorizedClientWhenSavedThenRemoved() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName2, mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNotNull();
this.authorizedClientService.removeAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
loadedAuthorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNull();
}
Reusable Method for MCI (click to expand)
private static Authentication createMockAuthentication(String principalName) {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(principalName);
return authentication;
}
Mock Clone Instance #spring-security_MCI_141
- Scope: method level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 4
- MO Count: 4
Reusable Method
private Authentication mockAuthentication;
@BeforeEach
public void setUp() {
mockAuthentication = mock(Authentication.class);
}
mockAuthentication
The refactoring details in each test cases
Test Case ID #spring-security_Test_141_1
Test Case Name: newSessionIsCreatedIfSessionAlreadyExistsWithEventPublisher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\DefaultSessionAuthenticationStrategyTests.java)
Mock Object Variable Name: mockAuthentication
Suggested Diff
@@
strategy.setApplicationEventPublisher(eventPublisher);
- Authentication mockAuthentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `mockAuthentication`
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
assertThat(oldSessionId.equals(request.getSession().getId())).isFalse();
assertThat(request.getSession().getAttribute("blah")).isNotNull();
assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
assertThat(eventArgumentCaptor.getValue()).isNotNull();
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue();
assertThat(event.getOldSessionId()).isEqualTo(oldSessionId);
assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId());
assertThat(event.getAuthentication()).isSameAs(mockAuthentication);
Original Test Code (click to expand)
@Test
public void newSessionIsCreatedIfSessionAlreadyExistsWithEventPublisher() {
SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
HttpServletRequest request = new MockHttpServletRequest();
HttpSession session = request.getSession();
session.setAttribute("blah", "blah");
session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest");
String oldSessionId = session.getId();
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
strategy.setApplicationEventPublisher(eventPublisher);
Authentication mockAuthentication = mock(Authentication.class);
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
assertThat(oldSessionId.equals(request.getSession().getId())).isFalse();
assertThat(request.getSession().getAttribute("blah")).isNotNull();
assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
assertThat(eventArgumentCaptor.getValue()).isNotNull();
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue();
assertThat(event.getOldSessionId()).isEqualTo(oldSessionId);
assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId());
assertThat(event.getAuthentication()).isSameAs(mockAuthentication);
}
Reusable Method for MCI (click to expand)
private Authentication mockAuthentication;
@BeforeEach
public void setUp() {
mockAuthentication = mock(Authentication.class);
}
mockAuthentication
Test Case ID #spring-security_Test_141_2
Test Case Name: onlySavedRequestAttributeIsMigratedIfMigrateAttributesIsFalseWithEventPublisher(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\DefaultSessionAuthenticationStrategyTests.java)
Mock Object Variable Name: mockAuthentication
Suggested Diff
@@
strategy.setApplicationEventPublisher(eventPublisher);
- Authentication mockAuthentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `mockAuthentication`
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
assertThat(request.getSession().getAttribute("blah")).isNull();
assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
assertThat(eventArgumentCaptor.getValue()).isNotNull();
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue();
assertThat(event.getOldSessionId()).isEqualTo(oldSessionId);
assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId());
assertThat(event.getAuthentication()).isSameAs(mockAuthentication);
Original Test Code (click to expand)
@Test
public void onlySavedRequestAttributeIsMigratedIfMigrateAttributesIsFalseWithEventPublisher() {
SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
strategy.setMigrateSessionAttributes(false);
HttpServletRequest request = new MockHttpServletRequest();
HttpSession session = request.getSession();
session.setAttribute("blah", "blah");
session.setAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY", "DefaultSavedRequest");
String oldSessionId = session.getId();
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);
strategy.setApplicationEventPublisher(eventPublisher);
Authentication mockAuthentication = mock(Authentication.class);
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
ArgumentCaptor<ApplicationEvent> eventArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class);
verify(eventPublisher).publishEvent(eventArgumentCaptor.capture());
assertThat(request.getSession().getAttribute("blah")).isNull();
assertThat(request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY")).isNotNull();
assertThat(eventArgumentCaptor.getValue()).isNotNull();
assertThat(eventArgumentCaptor.getValue() instanceof SessionFixationProtectionEvent).isTrue();
SessionFixationProtectionEvent event = (SessionFixationProtectionEvent) eventArgumentCaptor.getValue();
assertThat(event.getOldSessionId()).isEqualTo(oldSessionId);
assertThat(event.getNewSessionId()).isEqualTo(request.getSession().getId());
assertThat(event.getAuthentication()).isSameAs(mockAuthentication);
}
Reusable Method for MCI (click to expand)
private Authentication mockAuthentication;
@BeforeEach
public void setUp() {
mockAuthentication = mock(Authentication.class);
}
mockAuthentication
Test Case ID #spring-security_Test_141_3
Test Case Name: onAuthenticationWhenMigrateSessionAttributesTrueThenMaxInactiveIntervalIsMigrated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\DefaultSessionAuthenticationStrategyTests.java)
Mock Object Variable Name: mockAuthentication
Suggested Diff
@@
@Test
public void onAuthenticationWhenMigrateSessionAttributesTrueThenMaxInactiveIntervalIsMigrated() {
SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
HttpServletRequest request = new MockHttpServletRequest();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(1);
- Authentication mockAuthentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `mockAuthentication`
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
assertThat(request.getSession().getMaxInactiveInterval()).isEqualTo(1);
}
Original Test Code (click to expand)
@Test
public void onAuthenticationWhenMigrateSessionAttributesTrueThenMaxInactiveIntervalIsMigrated() {
SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
HttpServletRequest request = new MockHttpServletRequest();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(1);
Authentication mockAuthentication = mock(Authentication.class);
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
assertThat(request.getSession().getMaxInactiveInterval()).isEqualTo(1);
}
Reusable Method for MCI (click to expand)
private Authentication mockAuthentication;
@BeforeEach
public void setUp() {
mockAuthentication = mock(Authentication.class);
}
mockAuthentication
Test Case ID #spring-security_Test_141_4
Test Case Name: onAuthenticationWhenMigrateSessionAttributesFalseThenMaxInactiveIntervalIsNotMigrated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\DefaultSessionAuthenticationStrategyTests.java)
Mock Object Variable Name: mockAuthentication
Suggested Diff
@@
session.setMaxInactiveInterval(1);
- Authentication mockAuthentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `mockAuthentication`
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
assertThat(request.getSession().getMaxInactiveInterval()).isNotEqualTo(1);
Original Test Code (click to expand)
@Test
public void onAuthenticationWhenMigrateSessionAttributesFalseThenMaxInactiveIntervalIsNotMigrated() {
SessionFixationProtectionStrategy strategy = new SessionFixationProtectionStrategy();
strategy.setMigrateSessionAttributes(false);
HttpServletRequest request = new MockHttpServletRequest();
HttpSession session = request.getSession();
session.setMaxInactiveInterval(1);
Authentication mockAuthentication = mock(Authentication.class);
strategy.onAuthentication(mockAuthentication, request, new MockHttpServletResponse());
assertThat(request.getSession().getMaxInactiveInterval()).isNotEqualTo(1);
}
Reusable Method for MCI (click to expand)
private Authentication mockAuthentication;
@BeforeEach
public void setUp() {
mockAuthentication = mock(Authentication.class);
}
mockAuthentication
Mock Clone Instance #spring-security_MCI_142
- Scope: method level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 12
- MO Count: 12
Reusable Method
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
The refactoring details in each test cases
Test Case ID #spring-security_Test_142_1
Test Case Name: authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: a
Suggested Diff
@@
@Test
void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() {
- Authentication a = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
ProviderManager mgr = new ProviderManager(createProviderWhichReturns(a));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isEqualTo(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Original Test Code (click to expand)
@Test
void authenticationSucceedsWithSupportedTokenAndReturnsExpectedObject() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(createProviderWhichReturns(a));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isEqualTo(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_2
Test Case Name: authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: a
Suggested Diff
@@
@Test
void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() {
- Authentication a = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isSameAs(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Original Test Code (click to expand)
@Test
void authenticationSucceedsWhenFirstProviderReturnsNullButSecondAuthenticates() {
Authentication a = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichReturns(null), createProviderWhichReturns(a)));
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
Authentication result = mgr.authenticate(a);
assertThat(result).isSameAs(a);
verify(publisher).publishAuthenticationSuccess(result);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_3
Test Case Name: authenticationExceptionIsIgnoredIfLaterProviderAuthenticates(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void authenticationExceptionIsIgnoredIfLaterProviderAuthenticates() {
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(new BadCredentialsException("", new Throwable())), createProviderWhichReturns(a));
- assertThat(mgr.authenticate(mock(Authentication.class))).isSameAs(authReq);
+ assertThat(mgr.authenticate(mock(Authentication.class))).isSameAs(a);
}
Original Test Code (click to expand)
@Test
void authenticationExceptionIsIgnoredIfLaterProviderAuthenticates() {
Authentication authReq = mock(Authentication.class);
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(new BadCredentialsException("", new Throwable())), createProviderWhichReturns(authReq));
assertThat(mgr.authenticate(mock(Authentication.class))).isSameAs(authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_4
Test Case Name: parentAuthenticationIsUsedIfProvidersDontAuthenticate(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void parentAuthenticationIsUsedIfProvidersDontAuthenticate() {
AuthenticationManager parent = mock(AuthenticationManager.class);
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
given(parent.authenticate(a)).willReturn(a);
ProviderManager mgr = new ProviderManager(List.of(mock(AuthenticationProvider.class)), parent);
assertThat(mgr.authenticate(a)).isSameAs(a);
}
Original Test Code (click to expand)
@Test
void parentAuthenticationIsUsedIfProvidersDontAuthenticate() {
AuthenticationManager parent = mock(AuthenticationManager.class);
Authentication authReq = mock(Authentication.class);
given(parent.authenticate(authReq)).willReturn(authReq);
ProviderManager mgr = new ProviderManager(List.of(mock(AuthenticationProvider.class)), parent);
assertThat(mgr.authenticate(authReq)).isSameAs(authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_5
Test Case Name: providerNotFoundFromParentIsIgnored(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void providerNotFoundFromParentIsIgnored() {
- final Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
- given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
+ given(parent.authenticate(a)).willThrow(new ProviderNotFoundException(""));
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher);
- assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
+ assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(a)).satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, a));
}
Original Test Code (click to expand)
@Test
void providerNotFoundFromParentIsIgnored() {
final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
given(parent.authenticate(authReq)).willThrow(new ProviderNotFoundException(""));
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_6
Test Case Name: authenticationExceptionFromParentOverridesPreviousOnes(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void authenticationExceptionFromParentOverridesPreviousOnes() {
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be
// propagated
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
- given(parent.authenticate(authReq)).willThrow(expected);
+ given(parent.authenticate(a)).willThrow(expected);
- assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).isSameAs(expected);
+ assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(a)).isSameAs(expected);
}
Original Test Code (click to expand)
@Test
void authenticationExceptionFromParentOverridesPreviousOnes() {
AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException(""))), parent);
Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
given(parent.authenticate(authReq)).willThrow(expected);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq)).isSameAs(expected);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_7
Test Case Name: statusExceptionIsPublished(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void statusExceptionIsPublished() {
AuthenticationManager parent = mock(AuthenticationManager.class);
LockedException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(expected)), parent);
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
- assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
+ assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(a));
- verify(publisher).publishAuthenticationFailure(expected, authReq);
+ verify(publisher).publishAuthenticationFailure(expected, a);
}
Original Test Code (click to expand)
@Test
void statusExceptionIsPublished() {
AuthenticationManager parent = mock(AuthenticationManager.class);
LockedException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(List.of(createProviderWhichThrows(expected)), parent);
Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_8
Test Case Name: whenAccountStatusExceptionThenAuthenticationRequestIsIncluded(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void whenAccountStatusExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(a));
- assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
+ assertThat(expected.getAuthenticationRequest()).isEqualTo(a);
}
Original Test Code (click to expand)
@Test
void whenAccountStatusExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new LockedException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_9
Test Case Name: whenInternalServiceAuthenticationExceptionThenAuthenticationRequestIsIncluded(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void whenInternalServiceAuthenticationExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new InternalAuthenticationServiceException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> mgr.authenticate(a));
assertThat(expected.getAuthenticationRequest()).isEqualTo(a);
}
Original Test Code (click to expand)
@Test
void whenInternalServiceAuthenticationExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new InternalAuthenticationServiceException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> mgr.authenticate(authReq));
assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_10
Test Case Name: whenAuthenticationExceptionThenAuthenticationRequestIsIncluded(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
@Test
void whenAuthenticationExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new BadCredentialsException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq));
assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
@@
- assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq));
+ assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(a));
assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
@@
- assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
+ assertThat(expected.getAuthenticationRequest()).isEqualTo(a);
}
Original Test Code (click to expand)
@Test
void whenAuthenticationExceptionThenAuthenticationRequestIsIncluded() {
AuthenticationException expected = new BadCredentialsException("");
ProviderManager mgr = new ProviderManager(createProviderWhichThrows(expected));
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq));
assertThat(expected.getAuthenticationRequest()).isEqualTo(authReq);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_11
Test Case Name: providerThrowsInternalAuthenticationServiceException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
// SEC-2367
@Test
void providerThrowsInternalAuthenticationServiceException() {
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected), createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> mgr.authenticate(a));
}
Original Test Code (click to expand)
@Test
void providerThrowsInternalAuthenticationServiceException() {
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected), createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> mgr.authenticate(authReq));
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Test Case ID #spring-security_Test_142_12
Test Case Name: authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ProviderManagerTests.java)
Mock Object Variable Name: authReq
Suggested Diff
@@
parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher);
- Authentication authReq = mock(Authentication.class);
+ // removed local mock; replaced with global field `a`
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq)).isSameAs(badCredentialsExParent);
@@
- verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq);
+ verify(publisher).publishAuthenticationFailure(badCredentialsExParent, a);
// publishes
// Child should not publish (duplicate event)
- verifyNoMoreInteractions(publisher);
+ verifyNoMoreInteractions(publisher);
Original Test Code (click to expand)
@Test
void authenticateWhenFailsInParentAndPublishesThenChildDoesNotPublish() {
BadCredentialsException badCredentialsExParent = new BadCredentialsException("Bad Credentials in parent");
ProviderManager parentMgr = new ProviderManager(createProviderWhichThrows(badCredentialsExParent));
ProviderManager childMgr = new ProviderManager(List.of(createProviderWhichThrows(new BadCredentialsException("Bad Credentials in child"))), parentMgr);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher);
Authentication authReq = mock(Authentication.class);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq)).isSameAs(badCredentialsExParent);
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq);
verifyNoMoreInteractions(publisher);
}
Reusable Method for MCI (click to expand)
private Authentication a;
@BeforeEach
public void setUp() {
a = mock(Authentication.class);
}
a
Mock Clone Instance #spring-security_MCI_143
- Scope: method level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 3
- MO Count: 3
Reusable Method
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
The refactoring details in each test cases
Test Case ID #spring-security_Test_143_1
Test Case Name: deferredContext(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\InheritableThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void deferredContext() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
Supplier<SecurityContext> deferredContext = () -> new SecurityContextImpl(authentication);
this.strategy.setDeferredContext(deferredContext);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(deferredContext.get());
assertThat(this.strategy.getContext()).isEqualTo(deferredContext.get());
}
Original Test Code (click to expand)
@Test
void deferredContext() {
Authentication authentication = mock(Authentication.class);
Supplier<SecurityContext> deferredContext = () -> new SecurityContextImpl(authentication);
this.strategy.setDeferredContext(deferredContext);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(deferredContext.get());
assertThat(this.strategy.getContext()).isEqualTo(deferredContext.get());
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Test Case ID #spring-security_Test_143_2
Test Case Name: context(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\InheritableThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void context() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
SecurityContext context = new SecurityContextImpl(authentication);
this.strategy.setContext(context);
assertThat(this.strategy.getContext()).isEqualTo(context);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(context);
}
Original Test Code (click to expand)
@Test
void context() {
Authentication authentication = mock(Authentication.class);
SecurityContext context = new SecurityContextImpl(authentication);
this.strategy.setContext(context);
assertThat(this.strategy.getContext()).isEqualTo(context);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(context);
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Test Case ID #spring-security_Test_143_3
Test Case Name: getContextWhenEmptyThenReturnsSameInstance(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\InheritableThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void getContextWhenEmptyThenReturnsSameInstance() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
this.strategy.getContext().setAuthentication(authentication);
assertThat(this.strategy.getContext().getAuthentication()).isEqualTo(authentication);
}
Original Test Code (click to expand)
@Test
void getContextWhenEmptyThenReturnsSameInstance() {
Authentication authentication = mock(Authentication.class);
this.strategy.getContext().setAuthentication(authentication);
assertThat(this.strategy.getContext().getAuthentication()).isEqualTo(authentication);
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Mock Clone Instance #spring-security_MCI_144
- Scope: method level
- Mocked Class:
org.springframework.security.core.Authentication
- Test Case Count: 3
- MO Count: 3
Reusable Method
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
The refactoring details in each test cases
Test Case ID #spring-security_Test_144_1
Test Case Name: deferredContext(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void deferredContext() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
Supplier<SecurityContext> deferredContext = () -> new SecurityContextImpl(authentication);
this.strategy.setDeferredContext(deferredContext);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(deferredContext.get());
assertThat(this.strategy.getContext()).isEqualTo(deferredContext.get());
}
Original Test Code (click to expand)
@Test
void deferredContext() {
Authentication authentication = mock(Authentication.class);
Supplier<SecurityContext> deferredContext = () -> new SecurityContextImpl(authentication);
this.strategy.setDeferredContext(deferredContext);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(deferredContext.get());
assertThat(this.strategy.getContext()).isEqualTo(deferredContext.get());
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Test Case ID #spring-security_Test_144_2
Test Case Name: context(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void context() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
SecurityContext context = new SecurityContextImpl(authentication);
this.strategy.setContext(context);
assertThat(this.strategy.getContext()).isEqualTo(context);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(context);
}
Original Test Code (click to expand)
@Test
void context() {
Authentication authentication = mock(Authentication.class);
SecurityContext context = new SecurityContextImpl(authentication);
this.strategy.setContext(context);
assertThat(this.strategy.getContext()).isEqualTo(context);
assertThat(this.strategy.getDeferredContext().get()).isEqualTo(context);
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Test Case ID #spring-security_Test_144_3
Test Case Name: getContextWhenEmptyThenReturnsSameInstance(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ThreadLocalSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: authentication
Suggested Diff
@@
@Test
void getContextWhenEmptyThenReturnsSameInstance() {
- Authentication authentication = mock(Authentication.class);
+ // removed local mock; replaced with global field `authentication`
this.strategy.getContext().setAuthentication(authentication);
assertThat(this.strategy.getContext().getAuthentication()).isEqualTo(authentication);
}
Original Test Code (click to expand)
@Test
void getContextWhenEmptyThenReturnsSameInstance() {
Authentication authentication = mock(Authentication.class);
this.strategy.getContext().setAuthentication(authentication);
assertThat(this.strategy.getContext().getAuthentication()).isEqualTo(authentication);
}
Reusable Method for MCI (click to expand)
private Authentication authentication;
@BeforeEach
public void setUp() {
authentication = mock(Authentication.class);
}
authentication;
Mock Clone Instance #spring-security_MCI_145
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.core.OAuth2Token
- Test Case Count: 5
- MO Count: 5
Reusable Method
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
The refactoring details in each test cases
Test Case ID #spring-security_Test_145_1
Mock Object Variable Name: token
Suggested Diff
@@
@Test
public void validateWhenNoValidatorsConfiguredThenReturnsSuccessfulResult() {
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>();
- OAuth2Token token = mock(OAuth2Token.class);
+ // removed local mock; replaced with global field `token`
assertThat(tokenValidator.validate(token).hasErrors()).isFalse();
}
Original Test Code (click to expand)
@Test
public void validateWhenNoValidatorsConfiguredThenReturnsSuccessfulResult() {
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>();
OAuth2Token token = mock(OAuth2Token.class);
assertThat(tokenValidator.validate(token).hasErrors()).isFalse();
}
Reusable Method for MCI (click to expand)
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
Test Case ID #spring-security_Test_145_2
Test Case Name: validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: token
Suggested Diff
@@
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
- OAuth2Token token = mock(OAuth2Token.class);
+ // removed local mock; replaced with global field `token`
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
Original Test Code (click to expand)
@Test
public void validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator() {
OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class);
given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
}
Reusable Method for MCI (click to expand)
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
Test Case ID #spring-security_Test_145_3
Test Case Name: validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: token
Suggested Diff
@@
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
- OAuth2Token token = mock(OAuth2Token.class);
+ // removed local mock; replaced with global field `token`
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
Original Test Code (click to expand)
@Test
public void validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails() {
OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class);
OAuth2Error otherDetail = new OAuth2Error("another-error");
given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
given(secondFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(otherDetail));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
}
Reusable Method for MCI (click to expand)
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
Test Case ID #spring-security_Test_145_4
Mock Object Variable Name: token
Suggested Diff
@@
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
- OAuth2Token token = mock(OAuth2Token.class);
+ // removed local mock; replaced with global field `token`
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
Original Test Code (click to expand)
@Test
public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
}
Reusable Method for MCI (click to expand)
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
Test Case ID #spring-security_Test_145_5
Mock Object Variable Name: token
Suggested Diff
@@
DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess);
- OAuth2Token token = mock(OAuth2Token.class);
+ // removed local mock; replaced with global field `token`
firstValidator.validate(token);
secondValidator.validate(token);
verify(firstSuccess, times(2)).validate(token);
verify(secondSuccess, times(2)).validate(token);
Original Test Code (click to expand)
@Test
public void constructorsWhenInvokedWithSameInputsThenResultInSameOutputs() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess);
OAuth2Token token = mock(OAuth2Token.class);
firstValidator.validate(token);
secondValidator.validate(token);
verify(firstSuccess, times(2)).validate(token);
verify(secondSuccess, times(2)).validate(token);
}
Reusable Method for MCI (click to expand)
private OAuth2Token token;
@BeforeEach
public void setUp() {
token = mock(OAuth2Token.class);
}
token;
Mock Clone Instance #spring-security_MCI_146
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 3
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> createMockConverter(JwtBearerGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(grantRequest)).willReturn(parameters);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_146_1
Test Case Name: getTokenResponseWhenParametersConverterSetThenAbleToOverrideDefaultParameters(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenAbleToOverrideDefaultParameters() throws Exception {
this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> createMockConverter(JwtBearerGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(grantRequest)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_146_2
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
Set<String> scopes = clientRegistration.getScopes();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.JWT_BEARER.getValue()), param(OAuth2ParameterNames.ASSERTION, this.jwtAssertion.getTokenValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
Set<String> scopes = clientRegistration.getScopes();
JwtBearerGrantRequest grantRequest = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.JWT_BEARER.getValue()), param(OAuth2ParameterNames.ASSERTION, this.jwtAssertion.getTokenValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> createMockConverter(JwtBearerGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(grantRequest)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_146_3
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: addedParametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> addedParametersConverter = MockConverter.createMockConverter(request, parameters);
this.client.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", "custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.client.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", "custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> createMockConverter(JwtBearerGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(grantRequest)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_146_4
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveJwtBearerTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
- Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(request)).willReturn(parameters);
+ Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(request, parameters);
this.client.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
ClientRegistration clientRegistration = this.clientRegistration.build();
JwtBearerGrantRequest request = new JwtBearerGrantRequest(clientRegistration, this.jwtAssertion);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.client.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> createMockConverter(JwtBearerGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(grantRequest)).willReturn(parameters);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_147
- Scope: method level
- Mocked Class:
jakarta.servlet.AsyncContext
- Test Case Count: 3
- MO Count: 3
Reusable Method
private AsyncContext asyncContext;
@BeforeEach
public void setUp() {
asyncContext = mock(AsyncContext.class);
}
asyncContext;
The refactoring details in each test cases
Test Case ID #spring-security_Test_147_1
Test Case Name: getAsyncContextStart(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilterTests.java)
Mock Object Variable Name: asyncContext
Suggested Diff
@@
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
- AsyncContext asyncContext = mock(AsyncContext.class);
+ // removed local mock; replaced with global field `asyncContext`
given(this.request.getAsyncContext()).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().getAsyncContext().start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
- verify(asyncContext).start(runnableCaptor.capture());
+ verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
Original Test Code (click to expand)
@Test
public void getAsyncContextStart() throws Exception {
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
given(this.request.getAsyncContext()).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().getAsyncContext().start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
}
Reusable Method for MCI (click to expand)
private AsyncContext asyncContext;
@BeforeEach
public void setUp() {
asyncContext = mock(AsyncContext.class);
}
asyncContext;
Test Case ID #spring-security_Test_147_2
Test Case Name: startAsyncStart(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilterTests.java)
Mock Object Variable Name: asyncContext
Suggested Diff
@@
@Test
public void startAsyncStart() throws Exception {
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
- AsyncContext asyncContext = mock(AsyncContext.class);
+ // removed local mock; replaced with global field `asyncContext`
given(this.request.startAsync()).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().startAsync().start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
}
Original Test Code (click to expand)
@Test
public void startAsyncStart() throws Exception {
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
given(this.request.startAsync()).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().startAsync().start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
}
Reusable Method for MCI (click to expand)
private AsyncContext asyncContext;
@BeforeEach
public void setUp() {
asyncContext = mock(AsyncContext.class);
}
asyncContext;
Test Case ID #spring-security_Test_147_3
Test Case Name: startAsyncWithRequestResponseStart(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilterTests.java)
Mock Object Variable Name: asyncContext
Suggested Diff
@@
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
- AsyncContext asyncContext = mock(AsyncContext.class);
+ // removed local mock; replaced with global field `asyncContext`
given(this.request.startAsync(this.request, this.response)).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().startAsync(this.request, this.response).start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
Original Test Code (click to expand)
@Test
public void startAsyncWithRequestResponseStart() throws Exception {
ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
SecurityContext context = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
given(this.request.startAsync(this.request, this.response)).willReturn(asyncContext);
Runnable runnable = () -> {
};
wrappedRequest().startAsync(this.request, this.response).start(runnable);
verifyNoMoreInteractions(this.authenticationManager, this.logoutHandler);
verify(asyncContext).start(runnableCaptor.capture());
DelegatingSecurityContextRunnable wrappedRunnable = (DelegatingSecurityContextRunnable) runnableCaptor.getValue();
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegateSecurityContext")).isEqualTo(context);
assertThat(ReflectionTestUtils.getField(wrappedRunnable, "delegate"));
}
Reusable Method for MCI (click to expand)
private AsyncContext asyncContext;
@BeforeEach
public void setUp() {
asyncContext = mock(AsyncContext.class);
}
asyncContext;
Mock Clone Instance #spring-security_MCI_148
- Scope: method level
- Mocked Class:
org.springframework.security.web.access.WebInvocationPrivilegeEvaluator
- Test Case Count: 3
- MO Count: 3
Reusable Method
private WebInvocationPrivilegeEvaluator expected;
@BeforeEach
public void setUp() {
expected = mock(WebInvocationPrivilegeEvaluator.class);
}
expected
The refactoring details in each test cases
Test Case ID #spring-security_Test_148_1
Test Case Name: privilegeEvaluatorFromRequest(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: expected
Suggested Diff
@@
String uri = "/something";
- WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
+ // removed local mock; replaced with global field `expected`
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
- verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
+ verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromRequest() throws IOException {
WebApplicationContext wac = mock(WebApplicationContext.class);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
Reusable Method for MCI (click to expand)
private WebInvocationPrivilegeEvaluator expected;
@BeforeEach
public void setUp() {
expected = mock(WebInvocationPrivilegeEvaluator.class);
}
expected
Test Case ID #spring-security_Test_148_2
Test Case Name: privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: expected
Suggested Diff
@@
String uri = "/something";
- WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
+ // removed local mock; replaced with global field `expected`
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
- verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
+ verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
verify(strategy).getContext();
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy() throws IOException {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password", AuthorityUtils.NO_AUTHORITIES)));
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
wac.refresh();
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
private WebInvocationPrivilegeEvaluator expected;
@BeforeEach
public void setUp() {
expected = mock(WebInvocationPrivilegeEvaluator.class);
}
expected
Test Case ID #spring-security_Test_148_3
Test Case Name: privilegeEvaluatorFromChildContext(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: expected
Suggested Diff
@@
@Test
public void privilegeEvaluatorFromChildContext() throws IOException {
String uri = "/something";
- WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
+ // removed local mock; replaced with global field `expected`
this.tag.setUrl(uri);
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).willReturn(Collections.singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
this.tag.authorizeUsingUrlCheck();
- verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
+ verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromChildContext() throws IOException {
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class)).willReturn(Collections.singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
Reusable Method for MCI (click to expand)
private WebInvocationPrivilegeEvaluator expected;
@BeforeEach
public void setUp() {
expected = mock(WebInvocationPrivilegeEvaluator.class);
}
expected
Mock Clone Instance #spring-security_MCI_149
- Scope: class level
- Mocked Class:
io.micrometer.observation.ObservationHandler<io.micrometer.observation.Observation.Context>
- Test Case Count: 4
- MO Count: 4
Reusable Method
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_149_1
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(WebFilter filter, String expectedFilterNameTag) {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStop(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Original Test Code (click to expand)
@ParameterizedTest
@MethodSource("decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTagArguments")
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(WebFilter filter, String expectedFilterNameTag) {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationWebFilterChainDecorator decorator = new ObservationWebFilterChainDecorator(registry);
WebFilterChain chain = mock(WebFilterChain.class);
given(chain.filter(any())).willReturn(Mono.empty());
WebFilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/").build())).block();
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStop(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_149_2
Test Case Name: doFilterWhenMatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void doFilterWhenMatchesThenObservationRegistryObserves() {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenMatchesThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_149_3
Test Case Name: doFilterWhenMismatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void doFilterWhenMismatchesThenObservationRegistryObserves() {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenMismatchesThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
List<WebFilter> filters = Arrays.asList(new PassthroughWebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block();
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationWebFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_149_4
Test Case Name: doFilterWhenFilterExceptionThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
WebFilter error = mock(WebFilter.class);
given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException()));
List<WebFilter> filters = Arrays.asList(error);
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block());
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
WebFilter error = mock(WebFilter.class);
given(error.filter(any(), any())).willReturn(Mono.error(new IllegalStateException()));
List<WebFilter> filters = Arrays.asList(error);
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy fcp = new WebFilterChainProxy(chain);
fcp.setFilterChainDecorator(new ObservationWebFilterChainDecorator(registry));
WebFilter filter = WebFilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
WebFilterChain mockChain = mock(WebFilterChain.class);
given(mockChain.filter(any())).willReturn(Mono.empty());
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.filter(MockServerWebExchange.from(MockServerHttpRequest.get("/")), mockChain).block());
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Mock Clone Instance #spring-security_MCI_150
- Scope: class level
- Mocked Class:
io.micrometer.observation.ObservationHandler<io.micrometer.observation.Observation.Context>
- Test Case Count: 7
- MO Count: 7
Reusable Method
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_150_1
Test Case Name: doFilterWhenMatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
public void doFilterWhenMatchesThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
verify(handler, times(4)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
}
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenMatchesThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
verify(handler, times(4)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 1);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_2
Test Case Name: doFilterWhenMultipleFiltersThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
public void doFilterWhenMultipleFiltersThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mockFilter();
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
verify(handler, times(4)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 3);
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 3);
}
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenMultipleFiltersThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mockFilter();
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
verify(handler, times(4)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 3);
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.SECURED_OBSERVATION_NAME);
assertFilterChainObservation(contexts.next(), "after", 3);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_3
Test Case Name: doFilterWhenMismatchesThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
public void doFilterWhenMismatchesThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenMismatchesThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertThat(contexts.next().getName()).isEqualTo(ObservationFilterChainDecorator.UNSECURED_OBSERVATION_NAME);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_4
Test Case Name: doFilterWhenFilterExceptionThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
willThrow(IllegalStateException.class).given(this.filter).doFilter(any(), any(), any());
given(this.matcher.matches(any())).willReturn(true);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenFilterExceptionThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
willThrow(IllegalStateException.class).given(this.filter).doFilter(any(), any(), any());
given(this.matcher.matches(any())).willReturn(true);
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter));
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
verify(handler, atLeastOnce()).onError(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 1);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_5
Test Case Name: doFilterWhenExceptionWithMultipleFiltersThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
public void doFilterWhenExceptionWithMultipleFiltersThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mock(Filter.class);
willThrow(IllegalStateException.class).given(two).doFilter(any(), any(), any());
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 2);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenExceptionWithMultipleFiltersThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mock(Filter.class);
willThrow(IllegalStateException.class).given(two).doFilter(any(), any(), any());
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 2);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_6
Test Case Name: doFilterWhenOneFilterDoesNotProceedThenObservationRegistryObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\FilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
public void doFilterWhenOneFilterDoesNotProceedThenObservationRegistryObserves() throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mock(Filter.class);
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStart(captor.capture());
verify(handler, times(3)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 2);
assertFilterChainObservation(contexts.next(), "after", 3);
}
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenOneFilterDoesNotProceedThenObservationRegistryObserves() throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
given(this.matcher.matches(any())).willReturn(true);
Filter one = mockFilter();
Filter two = mock(Filter.class);
Filter three = mockFilter();
SecurityFilterChain sec = new DefaultSecurityFilterChain(this.matcher, one, two, three);
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStart(captor.capture());
verify(handler, times(3)).onStop(any());
Iterator<Observation.Context> contexts = captor.getAllValues().iterator();
assertThat(contexts.next().getName()).isEqualTo("wrap");
assertFilterChainObservation(contexts.next(), "before", 2);
assertFilterChainObservation(contexts.next(), "after", 3);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Test Case ID #spring-security_Test_150_7
Mock Object Variable Name: handler
Suggested Diff
@@
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(Filter filter, String expectedFilterNameTag) throws Exception {
- ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
- given(handler.supportsContext(any())).willReturn(true);
+ ObservationHandler<Observation.Context> handler = MockObservationHandler.createMockObservationHandler();
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onScopeClosed(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Original Test Code (click to expand)
@ParameterizedTest
@MethodSource("decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag")
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(Filter filter, String expectedFilterNameTag) throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onScopeClosed(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Reusable Method for MCI (click to expand)
public class MockObservationHandler {
public static ObservationHandler<Observation.Context> createMockObservationHandler() {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
return handler;
}
}
Mock Clone Instance #spring-security_MCI_151
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher
- Test Case Count: 3
- MO Count: 4
Reusable Method
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_151_1
Test Case Name: handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: matcher
Suggested Diff
@@
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
- ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
- given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
+ ServerWebExchangeMatcher matcher = createMockServerWebExchangeMatcher(this.exchange, MatchResult.notMatch());
given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(matcher, handler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(this.accessDeniedHandler).handle(this.exchange, null);
verify(handler, never()).handle(this.exchange, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(matcher, handler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(this.accessDeniedHandler).handle(this.exchange, null);
verify(handler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_151_2
Test Case Name: handleWhenFirstMatchesThenOnlyFirstInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstMatcher
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
- ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
- given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
+ ServerWebExchangeMatcher firstMatcher = createMockServerWebExchangeMatcher(this.exchange, MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
@@
Original Test Code (click to expand)
@Test
public void handleWhenFirstMatchesThenOnlyFirstInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.setDefaultAccessDeniedHandler(this.accessDeniedHandler);
this.delegator.handle(this.exchange, null).block();
verify(firstHandler).handle(this.exchange, null);
verify(secondHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
verify(secondMatcher, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_151_3
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: firstMatcher
Suggested Diff
@@
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
- ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
+ ServerWebExchangeMatcher firstMatcher = createMockServerWebExchangeMatcher(this.exchange, MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
@@
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_151_4
Test Case Name: handleWhenSecondMatchesThenOnlySecondInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java)
Mock Object Variable Name: secondMatcher
Suggested Diff
@@
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
- ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
- given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
+ ServerWebExchangeMatcher secondMatcher = createMockServerWebExchangeMatcher(this.exchange, MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
@@
Original Test Code (click to expand)
@Test
public void handleWhenSecondMatchesThenOnlySecondInvoked() {
ServerAccessDeniedHandler firstHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
this.entries.add(new DelegateEntry(firstMatcher, firstHandler));
this.entries.add(new DelegateEntry(secondMatcher, secondHandler));
this.delegator = new ServerWebExchangeDelegatingServerAccessDeniedHandler(this.entries);
this.delegator.handle(this.exchange, null).block();
verify(secondHandler).handle(this.exchange, null);
verify(firstHandler, never()).handle(this.exchange, null);
verify(this.accessDeniedHandler, never()).handle(this.exchange, null);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Mock Clone Instance #spring-security_MCI_152
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher
- Test Case Count: 2
- MO Count: 3
Reusable Method
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any())).willReturn(matchResult);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_152_1
Test Case Name: checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: match1
Suggested Diff
@@
@Test
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
- given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
+ this.match1 = createMockServerWebExchangeMatcher(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.match2, this.delegate2);
}
@@
Original Test Code (click to expand)
@Test
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.match2, this.delegate2);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any())).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_152_2
Test Case Name: checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: match1
Suggested Diff
@@
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
- given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.match1 = createMockServerWebExchangeMatcher(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
}
Original Test Code (click to expand)
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any())).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_152_3
Test Case Name: checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: match2
Suggested Diff
@@
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
- given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
+ this.match2 = createMockServerWebExchangeMatcher(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
}
@@
Original Test Code (click to expand)
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any())).willReturn(matchResult);
return matcher;
}
Mock Clone Instance #spring-security_MCI_153
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher
- Test Case Count: 9
- MO Count: 13
Reusable Method
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_153_1
Test Case Name: matchesWhenTrueTrueThenTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match(params1));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenTrueTrueThenTrue() {
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_2
Test Case Name: matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_3
Test Case Name: matchesWhenTrueFalseThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
Map<String, Object> params = Collections.singletonMap("foo", "bar");
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenTrueFalseThenFalse() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_4
Test Case Name: matchesWhenFalseTrueThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void matchesWhenFalseTrueThenFalse() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenFalseTrueThenFalse() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_5
Test Case Name: matchesWhenTrueTrueThenTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
- given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
+ this.matcher2 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenTrueTrueThenTrue() {
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_6
Test Case Name: matchesWhenTrueFalseThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\AndServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
- given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher2 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenTrueFalseThenFalse() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_7
Test Case Name: matchesWhenFalseThenTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\NegatedServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void matchesWhenFalseThenTrue() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenFalseThenTrue() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_8
Test Case Name: matchesWhenTrueThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\NegatedServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void matchesWhenTrueThenFalse() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenTrueThenFalse() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_9
Test Case Name: matchesWhenFalseFalseThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void matchesWhenFalseFalseThenFalse() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenFalseFalseThenFalse() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_10
Test Case Name: matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
Map<String, Object> params = Collections.singletonMap("foo", "bar");
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_11
Test Case Name: matchesWhenFalseTrueThenTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
Map<String, Object> params = Collections.singletonMap("foo", "bar");
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenFalseTrueThenTrue() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_12
Test Case Name: matchesWhenFalseFalseThenFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
@Test
public void matchesWhenFalseFalseThenFalse() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
- given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher2 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Original Test Code (click to expand)
@Test
public void matchesWhenFalseFalseThenFalse() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Test Case ID #spring-security_Test_153_13
Test Case Name: matchesWhenFalseTrueThenTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\util\matcher\OrServerWebExchangeMatcherTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
- given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
+ this.matcher2 = MockServerWebExchangeMatcher.createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
@@
Original Test Code (click to expand)
@Test
public void matchesWhenFalseTrueThenTrue() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerWebExchangeMatcher {
public static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = Mockito.mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
}
Mock Clone Instance #spring-security_MCI_154
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any(ServerWebExchange.class))).willReturn(matchResult);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_154_1
Test Case Name: filterWhenExchangeMismatchesThenNoRedirect(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\transport\HttpsRedirectWebFilterTests.java)
Mock Object Variable Name: matcher
Suggested Diff
@@
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
- ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
- given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ ServerWebExchangeMatcher matcher = createMockServerWebExchangeMatcher(ServerWebExchangeMatcher.MatchResult.notMatch());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(exchange.getResponse().getStatusCode()).isNull();
@@
Original Test Code (click to expand)
@Test
public void filterWhenExchangeMismatchesThenNoRedirect() {
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(exchange.getResponse().getStatusCode()).isNull();
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any(ServerWebExchange.class))).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_154_2
Test Case Name: filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\transport\HttpsRedirectWebFilterTests.java)
Mock Object Variable Name: matcher
Suggested Diff
@@
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
- ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
- given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.match());
+ ServerWebExchangeMatcher matcher = createMockServerWebExchangeMatcher(ServerWebExchangeMatcher.MatchResult.match());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443");
verify(matcher).matches(any(ServerWebExchange.class));
@@
Original Test Code (click to expand)
@Test
public void filterWhenExchangeMatchesAndRequestIsInsecureThenRedirects() {
given(this.chain.filter(any(ServerWebExchange.class))).willReturn(Mono.empty());
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any(ServerWebExchange.class))).willReturn(ServerWebExchangeMatcher.MatchResult.match());
this.filter.setRequiresHttpsRedirectMatcher(matcher);
ServerWebExchange exchange = get("http://localhost:8080");
this.filter.filter(exchange, this.chain).block();
assertThat(statusCode(exchange)).isEqualTo(302);
assertThat(redirectedUrl(exchange)).isEqualTo("https://localhost:8443");
verify(matcher).matches(any(ServerWebExchange.class));
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(any(ServerWebExchange.class))).willReturn(matchResult);
return matcher;
}
Mock Clone Instance #spring-security_MCI_155
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher
- Test Case Count: 2
- MO Count: 3
Reusable Method
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_155_1
Test Case Name: commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\DelegatingServerAuthenticationEntryPointTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult);
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2));
@@
Original Test Code (click to expand)
@Test
public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() {
Mono<Void> expectedResult = Mono.empty();
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult);
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2));
Mono<Void> actualResult = this.entryPoint.commence(this.exchange, this.e);
actualResult.block();
verifyNoMoreInteractions(this.delegate1);
verify(this.delegate2).commence(this.exchange, this.e);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_155_2
Test Case Name: commenceWhenNotMatchThenDefault(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\DelegatingServerAuthenticationEntryPointTests.java)
Mock Object Variable Name: matcher1
Suggested Diff
@@
@Test
public void commenceWhenNotMatchThenDefault() {
- given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
+ this.matcher1 = createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.notMatch());
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1));
this.entryPoint.commence(this.exchange, this.e).block();
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoMoreInteractions(this.delegate1);
}
Original Test Code (click to expand)
@Test
public void commenceWhenNotMatchThenDefault() {
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1));
this.entryPoint.commence(this.exchange, this.e).block();
assertThat(this.exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
verifyNoMoreInteractions(this.delegate1);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Test Case ID #spring-security_Test_155_3
Test Case Name: commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\DelegatingServerAuthenticationEntryPointTests.java)
Mock Object Variable Name: matcher2
Suggested Diff
@@
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
- given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
+ this.matcher2 = createMockServerWebExchangeMatcher(this.exchange, ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult);
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2));
Mono<Void> actualResult = this.entryPoint.commence(this.exchange, this.e);
Original Test Code (click to expand)
@Test
public void commenceWhenNotMatchThenMatchThenOnlySecondDelegateInvoked() {
Mono<Void> expectedResult = Mono.empty();
given(this.matcher1.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.matcher2.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.commence(this.exchange, this.e)).willReturn(expectedResult);
this.entryPoint = new DelegatingServerAuthenticationEntryPoint(new DelegateEntry(this.matcher1, this.delegate1), new DelegateEntry(this.matcher2, this.delegate2));
Mono<Void> actualResult = this.entryPoint.commence(this.exchange, this.e);
actualResult.block();
verifyNoMoreInteractions(this.delegate1);
verify(this.delegate2).commence(this.exchange, this.e);
}
Reusable Method for MCI (click to expand)
private static ServerWebExchangeMatcher createMockServerWebExchangeMatcher(ServerWebExchange exchange, Mono<ServerWebExchangeMatcher.MatchResult> matchResult) {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(exchange)).willReturn(matchResult);
return matcher;
}
Mock Clone Instance #spring-security_MCI_156
- Scope: method level
- Mocked Class:
org.springframework.security.rsocket.api.PayloadInterceptor
- Test Case Count: 11
- MO Count: 11
Reusable Method
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_156_1
Test Case Name: fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload)).then(() -> this.voidResult.assertWasNotSubscribed()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload)).then(() -> this.voidResult.assertWasNotSubscribed()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_2
Test Case Name: fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.interceptor2);
this.voidResult.assertWasNotSubscribed();
}
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptor1ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.interceptor2);
this.voidResult.assertWasNotSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_3
Test Case Name: requestResponseWhenInterceptorCompletesThenDelegateSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestResponseWhenInterceptorCompletesThenDelegateSubscribed() {
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
+ this.interceptor = createMockPayloadInterceptor(Mono.empty());
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload)).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
Original Test Code (click to expand)
@Test
public void requestResponseWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestResponse(any())).willReturn(this.payloadResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestResponse(this.payload)).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestResponse(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_4
Test Case Name: requestResponseWhenInterceptorErrorsThenDelegateNotInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.requestResponse(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.delegate);
}
Original Test Code (click to expand)
@Test
public void requestResponseWhenInterceptorErrorsThenDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.requestResponse(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verifyNoMoreInteractions(this.delegate);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_5
Test Case Name: requestStreamWhenInterceptorCompletesThenDelegateSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestStreamWhenInterceptorCompletesThenDelegateSubscribed() {
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
+ this.interceptor = createMockPayloadInterceptor(Mono.empty());
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Original Test Code (click to expand)
@Test
public void requestStreamWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestStream(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_6
Test Case Name: fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor2
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
- given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor2 = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_7
Test Case Name: requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertNoSubscribers()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Original Test Code (click to expand)
@Test
public void requestStreamWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestStream(this.payload)).then(() -> this.payloadResult.assertNoSubscribers()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_8
Test Case Name: requestChannelWhenInterceptorCompletesThenDelegateSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestChannelWhenInterceptorCompletesThenDelegateSubscribed() {
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
+ this.interceptor = createMockPayloadInterceptor(Mono.empty());
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload))).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
@@
Original Test Code (click to expand)
@Test
public void requestChannelWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.requestChannel(any())).willReturn(this.payloadResult.flux());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload))).then(() -> this.payloadResult.assertSubscribers()).then(() -> this.payloadResult.emit(this.payload)).expectNext(this.payload).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.delegate).requestChannel(any());
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_9
Test Case Name: requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload))).then(() -> this.payloadResult.assertNoSubscribers()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@@
Original Test Code (click to expand)
@Test
public void requestChannelWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.requestChannel(Flux.just(this.payload))).then(() -> this.payloadResult.assertNoSubscribers()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_10
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void metadataPushWhenInterceptorCompletesThenDelegateSubscribed() {
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
+ this.interceptor = createMockPayloadInterceptor(Mono.empty());
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasSubscribed()).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@@
Original Test Code (click to expand)
@Test
public void metadataPushWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willReturn(Mono.empty());
given(this.delegate.metadataPush(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasSubscribed()).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Test Case ID #spring-security_Test_156_11
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void metadataPushWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
+ this.interceptor = createMockPayloadInterceptor(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasNotSubscribed()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@@
Original Test Code (click to expand)
@Test
public void metadataPushWhenInterceptorErrorsThenDelegateNotSubscribed() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.metadataPush(this.payload)).then(() -> this.voidResult.assertWasNotSubscribed()).verifyErrorSatisfies((e) -> assertThat(e).isEqualTo(expected));
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Mono<?> interceptReturn) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willReturn(interceptReturn);
return interceptor;
}
Mock Clone Instance #spring-security_MCI_157
- Scope: method level
- Mocked Class:
org.springframework.security.rsocket.api.PayloadInterceptor
- Test Case Count: 4
- MO Count: 6
Reusable Method
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_157_1
Test Case Name: fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
// single interceptor
@Test
public void fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed() {
- given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor = createMockPayloadInterceptor(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload)).then(() -> this.voidResult.assertWasSubscribed()).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
@@
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorCompletesThenDelegateSubscribed() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor), this.metadataMimeType, this.dataMimeType);
StepVerifier.create(interceptor.fireAndForget(this.payload)).then(() -> this.voidResult.assertWasSubscribed()).verifyComplete();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Test Case ID #spring-security_Test_157_2
Test Case Name: fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
// multiple interceptors
@Test
public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() {
- given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor = createMockPayloadInterceptor(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
this.voidResult.assertWasSubscribed();
}
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
this.voidResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Test Case ID #spring-security_Test_157_3
Test Case Name: fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
- given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor = createMockPayloadInterceptor(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Test Case ID #spring-security_Test_157_4
Test Case Name: fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
- given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor = createMockPayloadInterceptor(withChainNext());
given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptor2ErrorsThenInterceptor2AndDelegateNotInvoked() {
RuntimeException expected = new RuntimeException("Oops");
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willReturn(Mono.error(expected));
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> interceptor.fireAndForget(this.payload).block()).isEqualTo(expected);
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
this.voidResult.assertWasNotSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Test Case ID #spring-security_Test_157_5
Test Case Name: fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor2
Suggested Diff
@@
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
- given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor2 = createMockPayloadInterceptor(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorsCompleteThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
this.voidResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Test Case ID #spring-security_Test_157_6
Test Case Name: fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked(File: C:\Java_projects\Spring\spring-security\rsocket\src\test\java\org\springframework\security\rsocket\core\PayloadInterceptorRSocketTests.java)
Mock Object Variable Name: interceptor2
Suggested Diff
@@
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
- given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
+ this.interceptor2 = createMockPayloadInterceptor(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
@@
Original Test Code (click to expand)
@Test
public void fireAndForgetWhenInterceptorsMutatesPayloadThenDelegateInvoked() {
given(this.interceptor.intercept(any(), any())).willAnswer(withChainNext());
given(this.interceptor2.intercept(any(), any())).willAnswer(withChainNext());
given(this.delegate.fireAndForget(any())).willReturn(this.voidResult.mono());
PayloadInterceptorRSocket interceptor = new PayloadInterceptorRSocket(this.delegate, Arrays.asList(this.interceptor, this.interceptor2), this.metadataMimeType, this.dataMimeType);
interceptor.fireAndForget(this.payload).block();
verify(this.interceptor).intercept(this.exchange.capture(), any());
assertThat(this.exchange.getValue().getPayload()).isEqualTo(this.payload);
verify(this.interceptor2).intercept(any(), any());
verify(this.delegate).fireAndForget(eq(this.payload));
this.voidResult.assertWasSubscribed();
}
Reusable Method for MCI (click to expand)
private static PayloadInterceptor createMockPayloadInterceptor(Answer<Mono<Void>> answer) {
PayloadInterceptor interceptor = mock(PayloadInterceptor.class);
given(interceptor.intercept(any(), any())).willAnswer(answer);
return interceptor;
}
Mock Clone Instance #spring-security_MCI_158
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(request)).willReturn(parameters);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_158_1
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientAuthorizationCodeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
- Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(request)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_158_2
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientAuthorizationCodeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
- Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()), param(OAuth2ParameterNames.CODE, "code"), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration, this.authorizationExchange);
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()), param(OAuth2ParameterNames.CODE, "code"), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(request)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_158_3
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveAuthorizationCodeTokenResponseClientTests.java)
Mock Object Variable Name: addedParametersConverter
Suggested Diff
@@
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
- Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> addedParametersConverter = MockConverter.createMockConverter(request, parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=authorization_code", "custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=authorization_code", "custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(request)).willReturn(parameters);
return converter;
}
}
Test Case ID #spring-security_Test_158_4
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveAuthorizationCodeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
- Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(request)).willReturn(parameters);
+ Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockConverter.createMockConverter(request, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
OAuth2AuthorizationCodeGrantRequest request = authorizationCodeGrantRequest();
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> createMockConverter(OAuth2AuthorizationCodeGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2AuthorizationCodeGrantRequest, MultiValueMap<String, String>> converter = mock();
given(converter.convert(request)).willReturn(parameters);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_159
- Scope: class level
- Mocked Class:
org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient<org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest>
- Test Case Count: 5
- MO Count: 5
Reusable Method
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_159_1
Test Case Name: authenticateWhenValidThenSuccess(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: accessTokenResponseClient
Suggested Diff
@@
@Test
public void authenticateWhenValidThenSuccess() {
- given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(this.tokenResponse.build()));
+ this.accessTokenResponseClient = MockReactiveOAuth2AccessTokenResponseClient.createMockAccessTokenResponseClient(Mono.just(this.tokenResponse.build()));
OAuth2AuthorizationCodeAuthenticationToken result = authenticate();
assertThat(result).isNotNull();
}
Original Test Code (click to expand)
@Test
public void authenticateWhenValidThenSuccess() {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(this.tokenResponse.build()));
OAuth2AuthorizationCodeAuthenticationToken result = authenticate();
assertThat(result).isNotNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
Test Case ID #spring-security_Test_159_2
Test Case Name: authenticationWhenOAuth2UserNotFoundThenEmpty(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: accessTokenResponseClient
Suggested Diff
@@
@Test
public void authenticationWhenOAuth2UserNotFoundThenEmpty() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
- given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
+ this.accessTokenResponseClient = MockReactiveOAuth2AccessTokenResponseClient.createMockAccessTokenResponseClient(Mono.just(accessTokenResponse));
given(this.userService.loadUser(any())).willReturn(Mono.empty());
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
}
Original Test Code (click to expand)
@Test
public void authenticationWhenOAuth2UserNotFoundThenEmpty() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.userService.loadUser(any())).willReturn(Mono.empty());
assertThat(this.manager.authenticate(loginToken()).block()).isNull();
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
Test Case ID #spring-security_Test_159_3
Test Case Name: authenticationWhenOAuth2UserFoundThenSuccess(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: accessTokenResponseClient
Suggested Diff
@@
@Test
public void authenticationWhenOAuth2UserFoundThenSuccess() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
- given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
+ this.accessTokenResponseClient = MockReactiveOAuth2AccessTokenResponseClient.createMockAccessTokenResponseClient(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
assertThat(result.isAuthenticated()).isTrue();
}
@@
Original Test Code (click to expand)
@Test
public void authenticationWhenOAuth2UserFoundThenSuccess() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities());
assertThat(result.isAuthenticated()).isTrue();
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
Test Case ID #spring-security_Test_159_4
Test Case Name: authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: accessTokenResponseClient
Suggested Diff
@@
additionalParameters.put("param2", "value2");
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).build();
- given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
+ this.accessTokenResponseClient = MockReactiveOAuth2AccessTokenResponseClient.createMockAccessTokenResponseClient(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
this.manager.authenticate(loginToken()).block();
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
Map<String, Object> additionalParameters = new HashMap<>();
additionalParameters.put("param1", "value1");
additionalParameters.put("param2", "value2");
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(additionalParameters).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
this.manager.authenticate(loginToken()).block();
assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
Test Case ID #spring-security_Test_159_5
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: accessTokenResponseClient
Suggested Diff
@@
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
- given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
+ this.accessTokenResponseClient = MockReactiveOAuth2AccessTokenResponseClient.createMockAccessTokenResponseClient(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.manager.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
public class MockReactiveOAuth2AccessTokenResponseClient {
public static ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> createMockAccessTokenResponseClient(Mono<OAuth2AccessTokenResponse> tokenResponseMono) {
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = Mockito.mock(ReactiveOAuth2AccessTokenResponseClient.class);
given(accessTokenResponseClient.getTokenResponse(any())).willReturn(tokenResponseMono);
return accessTokenResponseClient;
}
}
Mock Clone Instance #spring-security_MCI_160
- Scope: method level
- Mocked Class:
java.util.function.Function<org.springframework.security.oauth2.client.OAuth2AuthorizationContext, reactor.core.publisher.Mono<org.springframework.security.oauth2.core.OAuth2Token>>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> createMockTokenResolver(Mono<OAuth2Token> tokenMono) {
Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenMono);
return tokenResolver;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_160_1
Test Case Name: authorizeWhenCustomSubjectTokenResolverSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: subjectTokenResolver
Suggested Diff
@@
@Test
public void authorizeWhenCustomSubjectTokenResolverSetThenCalled() {
- Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver = mock(Function.class);
- given(subjectTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(Mono.just(this.subjectToken));
+ Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver = createMockTokenResolver(Mono.just(this.subjectToken));
this.authorizedClientProvider.setSubjectTokenResolver(subjectTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(Mono.just(accessTokenResponse));
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(subjectTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isNull();
}
@@
Original Test Code (click to expand)
@Test
public void authorizeWhenCustomSubjectTokenResolverSetThenCalled() {
Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> subjectTokenResolver = mock(Function.class);
given(subjectTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(Mono.just(this.subjectToken));
this.authorizedClientProvider.setSubjectTokenResolver(subjectTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(Mono.just(accessTokenResponse));
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(subjectTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isNull();
}
Reusable Method for MCI (click to expand)
private static Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> createMockTokenResolver(Mono<OAuth2Token> tokenMono) {
Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenMono);
return tokenResolver;
}
Test Case ID #spring-security_Test_160_2
Test Case Name: authorizeWhenCustomActorTokenResolverSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: actorTokenResolver
Suggested Diff
@@
public void authorizeWhenCustomActorTokenResolverSetThenCalled() {
- Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver = mock(Function.class);
- given(actorTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(Mono.just(this.actorToken));
+ Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver = createMockTokenResolver(Mono.just(this.actorToken));
this.authorizedClientProvider.setActorTokenResolver(actorTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(actorTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isEqualTo(this.actorToken);
}
Original Test Code (click to expand)
@Test
public void authorizeWhenCustomActorTokenResolverSetThenCalled() {
Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> actorTokenResolver = mock(Function.class);
given(actorTokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(Mono.just(this.actorToken));
this.authorizedClientProvider.setActorTokenResolver(actorTokenResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().refreshToken("refresh").build();
given(this.accessTokenResponseClient.getTokenResponse(any(TokenExchangeGrantRequest.class))).willReturn(Mono.just(accessTokenResponse));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(authorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
verify(actorTokenResolver).apply(authorizationContext);
ArgumentCaptor<TokenExchangeGrantRequest> grantRequestCaptor = ArgumentCaptor.forClass(TokenExchangeGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(grantRequestCaptor.capture());
TokenExchangeGrantRequest grantRequest = grantRequestCaptor.getValue();
assertThat(grantRequest.getSubjectToken()).isEqualTo(this.subjectToken);
assertThat(grantRequest.getActorToken()).isEqualTo(this.actorToken);
}
Reusable Method for MCI (click to expand)
private static Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> createMockTokenResolver(Mono<OAuth2Token> tokenMono) {
Function<OAuth2AuthorizationContext, Mono<OAuth2Token>> tokenResolver = mock(Function.class);
given(tokenResolver.apply(any(OAuth2AuthorizationContext.class))).willReturn(tokenMono);
return tokenResolver;
}
Mock Clone Instance #spring-security_MCI_161
- Scope: method level
- Mocked Class:
org.springframework.security.web.server.firewall.ServerExchangeRejectedHandler
- Test Case Count: 3
- MO Count: 3
Reusable Method
private ServerExchangeRejectedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(ServerExchangeRejectedHandler.class);
}
handler
The refactoring details in each test cases
Test Case ID #spring-security_Test_161_1
Test Case Name: doFilterWhenCustomFirewallThenInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
void doFilterWhenCustomFirewallThenInvoked() {
List<WebFilter> filters = Arrays.asList(new Http200WebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
- ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
+ // removed local mock; replaced with global field `handler`
ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class);
filter.setFirewall(firewall);
filter.setExchangeRejectedHandler(handler);
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
verify(firewall).getFirewalledExchange(any());
verifyNoInteractions(handler);
}
Original Test Code (click to expand)
@Test
void doFilterWhenCustomFirewallThenInvoked() {
List<WebFilter> filters = Arrays.asList(new Http200WebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class);
filter.setFirewall(firewall);
filter.setExchangeRejectedHandler(handler);
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
verify(firewall).getFirewalledExchange(any());
verifyNoInteractions(handler);
}
Reusable Method for MCI (click to expand)
private ServerExchangeRejectedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(ServerExchangeRejectedHandler.class);
}
handler
Test Case ID #spring-security_Test_161_2
Test Case Name: doFilterWhenCustomExchangeRejectedHandlerThenInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
@Test
void doFilterWhenCustomExchangeRejectedHandlerThenInvoked() {
List<WebFilter> filters = Arrays.asList(new Http200WebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
- ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
+ // removed local mock; replaced with global field `handler`
ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class);
given(firewall.getFirewalledExchange(any())).willReturn(Mono.error(new ServerExchangeRejectedException("Oops")));
filter.setFirewall(firewall);
filter.setExchangeRejectedHandler(handler);
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
verify(firewall).getFirewalledExchange(any());
- verify(handler).handle(any(), any());
+ verify(handler).handle(any(), any());
}
Original Test Code (click to expand)
@Test
void doFilterWhenCustomExchangeRejectedHandlerThenInvoked() {
List<WebFilter> filters = Arrays.asList(new Http200WebFilter());
ServerWebExchangeMatcher notMatch = (exchange) -> MatchResult.notMatch();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(notMatch, filters);
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
ServerWebExchangeFirewall firewall = mock(ServerWebExchangeFirewall.class);
given(firewall.getFirewalledExchange(any())).willReturn(Mono.error(new ServerExchangeRejectedException("Oops")));
filter.setFirewall(firewall);
filter.setExchangeRejectedHandler(handler);
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
verify(firewall).getFirewalledExchange(any());
verify(handler).handle(any(), any());
}
Reusable Method for MCI (click to expand)
private ServerExchangeRejectedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(ServerExchangeRejectedHandler.class);
}
handler
Test Case ID #spring-security_Test_161_3
Test Case Name: doFilterWhenDelayedServerExchangeRejectedException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\WebFilterChainProxyTests.java)
Mock Object Variable Name: handler
Suggested Diff
@@
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
- ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
+ // removed local mock; replaced with global field `handler`
filter.setExchangeRejectedHandler(handler);
// @formatter:off
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
// @formatter:on
verify(handler).handle(any(), any());
Original Test Code (click to expand)
@Test
void doFilterWhenDelayedServerExchangeRejectedException() {
List<WebFilter> filters = Arrays.asList(new WebFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Mono.error(new ServerExchangeRejectedException("Ooops"));
}
});
ServerWebExchangeMatcher match = (exchange) -> MatchResult.match();
MatcherSecurityWebFilterChain chain = new MatcherSecurityWebFilterChain(match, filters);
WebFilterChainProxy filter = new WebFilterChainProxy(chain);
ServerExchangeRejectedHandler handler = mock(ServerExchangeRejectedHandler.class);
filter.setExchangeRejectedHandler(handler);
WebTestClient.bindToController(new Object()).webFilter(filter).build().get().exchange();
verify(handler).handle(any(), any());
}
Reusable Method for MCI (click to expand)
private ServerExchangeRejectedHandler handler;
@BeforeEach
public void setUp() {
handler = mock(ServerExchangeRejectedHandler.class);
}
handler
Mock Clone Instance #spring-security_MCI_162
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> createMockConverter(OAuth2RefreshTokenGrantRequest request, HttpHeaders headers) {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_162_1
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> createMockConverter(OAuth2RefreshTokenGrantRequest request, HttpHeaders headers) {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_162_2
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(headersConverter.convert(grantRequest)).willReturn(headers);
+ Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2RefreshTokenGrantRequest grantRequest = new OAuth2RefreshTokenGrantRequest(clientRegistration, this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> createMockConverter(OAuth2RefreshTokenGrantRequest request, HttpHeaders headers) {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_162_3
Suggested Diff
@@
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
- Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
- given(addedHeadersConverter.convert(request)).willReturn(headers);
+ Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> addedHeadersConverter = MockConverter.createMockConverter(request, headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> addedHeadersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(addedHeadersConverter.convert(request)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(addedHeadersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(addedHeadersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(actualRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> createMockConverter(OAuth2RefreshTokenGrantRequest request, HttpHeaders headers) {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Test Case ID #spring-security_Test_162_4
Suggested Diff
@@
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
ClientRegistration clientRegistration = request.getClientRegistration();
- Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter1 = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
- given(headersConverter1.convert(request)).willReturn(headers);
+ Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter1 = MockConverter.createMockConverter(request, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter1);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter1).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
OAuth2RefreshTokenGrantRequest request = new OAuth2RefreshTokenGrantRequest(this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
ClientRegistration clientRegistration = request.getClientRegistration();
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> headersConverter1 = mock();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
given(headersConverter1.convert(request)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter1);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.tokenResponseClient.getTokenResponse(request).block();
verify(headersConverter1).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> createMockConverter(OAuth2RefreshTokenGrantRequest request, HttpHeaders headers) {
Converter<OAuth2RefreshTokenGrantRequest, HttpHeaders> converter = mock();
given(converter.convert(request)).willReturn(headers);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_163
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 3
- MO Count: 5
Reusable Method
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_163_1
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
- Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_163_2
Test Case Name: getTokenResponseWhenParametersConverterSetThenAbleToOverrideDefaultParameters(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
- Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.GRANT_TYPE, "custom");
parameters.set(OAuth2ParameterNames.SCOPE, "one two");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter((authorizationGrantRequest) -> parameters);
this.tokenResponseClient.getTokenResponse(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, "custom"), param(OAuth2ParameterNames.CLIENT_ID, "client-1"), param(OAuth2ParameterNames.SCOPE, "one two"));
// @formatter:on
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenAbleToOverrideDefaultParameters() throws Exception {
this.clientRegistration.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST);
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.GRANT_TYPE, "custom");
parameters.set(OAuth2ParameterNames.SCOPE, "one two");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter((authorizationGrantRequest) -> parameters);
this.tokenResponseClient.getTokenResponse(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, "custom"), param(OAuth2ParameterNames.CLIENT_ID, "client-1"), param(OAuth2ParameterNames.SCOPE, "one two"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_163_3
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
- Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
Set<String> scopes = clientRegistration.getScopes();
OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration);
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_163_4
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: addedParametersConverter
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
- Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> addedParametersConverter = MockParametersConverter.createMockParametersConverter(request, parameters);
this.client.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials", "custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> addedParametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(addedParametersConverter.convert(request)).willReturn(parameters);
this.client.addParametersConverter(addedParametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(addedParametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("grant_type=client_credentials", "custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_163_5
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveClientCredentialsTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
- Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(request)).willReturn(parameters);
+ Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(request, parameters);
this.client.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(this.clientRegistration.build());
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(request)).willReturn(parameters);
this.client.setParametersConverter(parametersConverter);
this.server.enqueue(MockResponses.json("access-token-response.json"));
this.client.getTokenResponse(request).block();
verify(parametersConverter).convert(request);
RecordedRequest actualRequest = this.server.takeRequest();
assertThat(actualRequest.getBody().readUtf8()).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(OAuth2ClientCredentialsGrantRequest request, MultiValueMap<String, String> parameters) {
Converter<OAuth2ClientCredentialsGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(request)).willReturn(parameters);
return parametersConverter;
}
}
Mock Clone Instance #spring-security_MCI_164
- Scope: class level
- Mocked Class:
org.springframework.security.core.context.SecurityContextHolderStrategy
- Test Case Count: 2
- MO Count: 3
Reusable Method
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_164_1
Test Case Name: changePasswordWhenCustomSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\provisioning\InMemoryUserDetailsManagerTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
Authentication authentication = TestAuthentication.authenticatedUser();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager((User) authentication.getPrincipal());
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(authentication);
manager.setSecurityContextHolderStrategy(strategy);
manager.changePassword("password", "newpassword");
verify(strategy).getContext();
}
Original Test Code (click to expand)
@Test
public void changePasswordWhenCustomSecurityContextHolderStrategyThenUses() {
Authentication authentication = TestAuthentication.authenticatedUser();
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager((User) authentication.getPrincipal());
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
manager.setSecurityContextHolderStrategy(strategy);
manager.changePassword("password", "newpassword");
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Test Case ID #spring-security_Test_164_2
Test Case Name: createUserWhenInstanceOfMutableUserDetailsThenChangePasswordWorks(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\provisioning\InMemoryUserDetailsManagerTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
CustomUser user = new CustomUser(User.withUserDetails(PasswordEncodedUser.user()).build());
Authentication authentication = TestAuthentication.authenticated(user);
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(authentication);
manager.setSecurityContextHolderStrategy(strategy);
manager.createUser(user);
String newPassword = "newPassword";
manager.changePassword(user.getPassword(), newPassword);
assertThat(manager.loadUserByUsername(user.getUsername()).getPassword()).isEqualTo(newPassword);
@@
Original Test Code (click to expand)
@Test
public void createUserWhenInstanceOfMutableUserDetailsThenChangePasswordWorks() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
CustomUser user = new CustomUser(User.withUserDetails(PasswordEncodedUser.user()).build());
Authentication authentication = TestAuthentication.authenticated(user);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
manager.setSecurityContextHolderStrategy(strategy);
manager.createUser(user);
String newPassword = "newPassword";
manager.changePassword(user.getPassword(), newPassword);
assertThat(manager.loadUserByUsername(user.getUsername()).getPassword()).isEqualTo(newPassword);
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Test Case ID #spring-security_Test_164_3
Test Case Name: changePasswordWhenCustomSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\provisioning\JdbcUserDetailsManagerTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
insertJoe();
Authentication authentication = authenticateJoe();
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
- given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(authentication);
+ given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
this.manager.setSecurityContextHolderStrategy(strategy);
this.manager.changePassword("wrongpassword", "newPassword");
verify(strategy).getContext();
@@
Original Test Code (click to expand)
@Test
public void changePasswordWhenCustomSecurityContextHolderStrategyThenUses() {
insertJoe();
Authentication authentication = authenticateJoe();
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
this.manager.setSecurityContextHolderStrategy(strategy);
this.manager.changePassword("wrongpassword", "newPassword");
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Mock Clone Instance #spring-security_MCI_165
- Scope: class level
- Mocked Class:
org.springframework.security.core.context.SecurityContextHolderStrategy
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_165_1
Test Case Name: privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTagTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
public void privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy() throws IOException {
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password", AuthorityUtils.NO_AUTHORITIES)));
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(
+ new TestingAuthenticationToken("user", "password", AuthorityUtils.NO_AUTHORITIES)
+ );
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
wac.refresh();
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
verify(strategy).getContext();
}
Original Test Code (click to expand)
@Test
public void privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy() throws IOException {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password", AuthorityUtils.NO_AUTHORITIES)));
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
wac.refresh();
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Test Case ID #spring-security_Test_165_2
Test Case Name: securityContextHolderStrategyIsUsedIfConfigured(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AccessControlListTagTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void securityContextHolderStrategyIsUsedIfConfigured() throws Exception {
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(this.bob));
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(this.bob);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
context.registerBean(PermissionEvaluator.class, () -> this.pe);
context.refresh();
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
this.pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(), new MockHttpServletResponse());
this.tag.setPageContext(this.pageContext);
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(strategy).getContext();
}
@@
Original Test Code (click to expand)
@Test
public void securityContextHolderStrategyIsUsedIfConfigured() throws Exception {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(this.bob));
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
context.registerBean(PermissionEvaluator.class, () -> this.pe);
context.refresh();
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
this.pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(), new MockHttpServletResponse());
this.tag.setPageContext(this.pageContext);
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Test Case ID #spring-security_Test_165_3
Test Case Name: setSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\taglibs\src\test\java\org\springframework\security\taglibs\authz\AuthenticationTagTests.java)
Mock Object Variable Name: strategy
Suggested Diff
@@
@Test
public void setSecurityContextHolderStrategyThenUses() throws Exception {
- SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
- given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES)));
+ SecurityContextHolderStrategy strategy = MockSecurityContextHolderStrategy.createMockSecurityContextHolderStrategy(
+ new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES));
MockServletContext servletContext = new MockServletContext();
GenericWebApplicationContext applicationContext = new GenericWebApplicationContext();
applicationContext.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
applicationContext.refresh();
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
this.authenticationTag.setPageContext(new MockPageContext(servletContext));
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodAsString");
verify(strategy).getContext();
}
@@
Original Test Code (click to expand)
@Test
public void setSecurityContextHolderStrategyThenUses() throws Exception {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES)));
MockServletContext servletContext = new MockServletContext();
GenericWebApplicationContext applicationContext = new GenericWebApplicationContext();
applicationContext.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
applicationContext.refresh();
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
this.authenticationTag.setPageContext(new MockPageContext(servletContext));
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodAsString");
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
public class MockSecurityContextHolderStrategy {
public static SecurityContextHolderStrategy createMockSecurityContextHolderStrategy(Authentication authentication) {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authentication));
return strategy;
}
}
Mock Clone Instance #spring-security_MCI_166
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<Object, Object> createMockConverterThatThrows() {
Converter<Object, Object> converter = mock(Converter.class);
given(converter.convert(any())).willThrow(RuntimeException.class);
return converter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_166_1
Test Case Name: readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\http\converter\OAuth2AccessTokenResponseHttpMessageConverterTests.java)
Mock Object Variable Name: tokenResponseConverter
Suggested Diff
@@
@Test
public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() {
- Converter tokenResponseConverter = mock(Converter.class);
- given(tokenResponseConverter.convert(any())).willThrow(RuntimeException.class);
+ Converter<Object, Object> tokenResponseConverter = MockConverter.createMockConverterThatThrows();
this.messageConverter.setAccessTokenResponseConverter(tokenResponseConverter);
String tokenResponse = "{}";
MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> this.messageConverter.readInternal(OAuth2AccessTokenResponse.class, response)).withMessageContaining("An error occurred reading the OAuth 2.0 Access Token Response");
}
@@
Original Test Code (click to expand)
@Test
public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() {
Converter tokenResponseConverter = mock(Converter.class);
given(tokenResponseConverter.convert(any())).willThrow(RuntimeException.class);
this.messageConverter.setAccessTokenResponseConverter(tokenResponseConverter);
String tokenResponse = "{}";
MockClientHttpResponse response = new MockClientHttpResponse(tokenResponse.getBytes(), HttpStatus.OK);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> this.messageConverter.readInternal(OAuth2AccessTokenResponse.class, response)).withMessageContaining("An error occurred reading the OAuth 2.0 Access Token Response");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<Object, Object> createMockConverterThatThrows() {
Converter<Object, Object> converter = mock(Converter.class);
given(converter.convert(any())).willThrow(RuntimeException.class);
return converter;
}
}
Test Case ID #spring-security_Test_166_2
Test Case Name: writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\http\converter\OAuth2AccessTokenResponseHttpMessageConverterTests.java)
Mock Object Variable Name: tokenResponseParametersConverter
Suggested Diff
@@
public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() {
- Converter tokenResponseParametersConverter = mock(Converter.class);
- given(tokenResponseParametersConverter.convert(any())).willThrow(RuntimeException.class);
+ Converter tokenResponseParametersConverter = MockConverter.createMockConverterThatThrows();
this.messageConverter.setAccessTokenResponseParametersConverter(tokenResponseParametersConverter);
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(Instant.now().plusSeconds(3600).toEpochMilli()).build();
// @formatter:on
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> this.messageConverter.writeInternal(accessTokenResponse, outputMessage)).withMessageContaining("An error occurred writing the OAuth 2.0 Access Token Response");
}
Original Test Code (click to expand)
@Test
public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() {
Converter tokenResponseParametersConverter = mock(Converter.class);
given(tokenResponseParametersConverter.convert(any())).willThrow(RuntimeException.class);
this.messageConverter.setAccessTokenResponseParametersConverter(tokenResponseParametersConverter);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(Instant.now().plusSeconds(3600).toEpochMilli()).build();
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> this.messageConverter.writeInternal(accessTokenResponse, outputMessage)).withMessageContaining("An error occurred writing the OAuth 2.0 Access Token Response");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<Object, Object> createMockConverterThatThrows() {
Converter<Object, Object> converter = mock(Converter.class);
given(converter.convert(any())).willThrow(RuntimeException.class);
return converter;
}
}
Test Case ID #spring-security_Test_166_3
Test Case Name: readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverterTests.java)
Mock Object Variable Name: errorConverter
Suggested Diff
@@
public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() {
- Converter errorConverter = mock(Converter.class);
- given(errorConverter.convert(any())).willThrow(RuntimeException.class);
+ Converter errorConverter = MockConverter.createMockConverterThatThrows();
this.messageConverter.setErrorConverter(errorConverter);
String errorResponse = "{}";
MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> this.messageConverter.readInternal(OAuth2Error.class, response)).withMessageContaining("An error occurred reading the OAuth 2.0 Error");
}
Original Test Code (click to expand)
@Test
public void readInternalWhenConversionFailsThenThrowHttpMessageNotReadableException() {
Converter errorConverter = mock(Converter.class);
given(errorConverter.convert(any())).willThrow(RuntimeException.class);
this.messageConverter.setErrorConverter(errorConverter);
String errorResponse = "{}";
MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> this.messageConverter.readInternal(OAuth2Error.class, response)).withMessageContaining("An error occurred reading the OAuth 2.0 Error");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<Object, Object> createMockConverterThatThrows() {
Converter<Object, Object> converter = mock(Converter.class);
given(converter.convert(any())).willThrow(RuntimeException.class);
return converter;
}
}
Test Case ID #spring-security_Test_166_4
Test Case Name: writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverterTests.java)
Mock Object Variable Name: errorParametersConverter
Suggested Diff
@@
@Test
public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() {
- Converter errorParametersConverter = mock(Converter.class);
- given(errorParametersConverter.convert(any())).willThrow(RuntimeException.class);
+ Converter<Object, Object> errorParametersConverter = MockConverter.createMockConverterThatThrows();
this.messageConverter.setErrorParametersConverter(errorParametersConverter);
OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", "https://tools.ietf.org/html/rfc6749#section-5.2");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> this.messageConverter.writeInternal(oauth2Error, outputMessage)).withMessageContaining("An error occurred writing the OAuth 2.0 Error");
}
@@
Original Test Code (click to expand)
@Test
public void writeInternalWhenConversionFailsThenThrowHttpMessageNotWritableException() {
Converter errorParametersConverter = mock(Converter.class);
given(errorParametersConverter.convert(any())).willThrow(RuntimeException.class);
this.messageConverter.setErrorParametersConverter(errorParametersConverter);
OAuth2Error oauth2Error = new OAuth2Error("unauthorized_client", "The client is not authorized", "https://tools.ietf.org/html/rfc6749#section-5.2");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
assertThatExceptionOfType(HttpMessageNotWritableException.class).isThrownBy(() -> this.messageConverter.writeInternal(oauth2Error, outputMessage)).withMessageContaining("An error occurred writing the OAuth 2.0 Error");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<Object, Object> createMockConverterThatThrows() {
Converter<Object, Object> converter = mock(Converter.class);
given(converter.convert(any())).willThrow(RuntimeException.class);
return converter;
}
}
Mock Clone Instance #spring-security_MCI_167
- Scope: class level
- Mocked Class:
org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository
- Test Case Count: 14
- MO Count: 14
Reusable Method
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_167_1
Test Case Name: resolveWhenClientRegistrationFoundThenWorks(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
public void resolveWhenClientRegistrationFoundThenWorks() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(this.registration));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/not-found-id");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void resolveWhenClientRegistrationFoundThenWorks() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/not-found-id");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_2
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenForwardedHeadersClientRegistrationFoundThenWorks() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(this.registration));
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> httpRequest = MockServerHttpRequest.get("/oauth2/authorization/id").header("X-Forwarded-Host", "evil.com");
// @formatter:on
ServerWebExchange exchange = MockServerWebExchange.from(httpRequest);
OAuth2AuthorizationRequest request = this.resolver.resolve(exchange).block();
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void resolveWhenForwardedHeadersClientRegistrationFoundThenWorks() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.registration));
MockServerHttpRequest.BaseBuilder<?> httpRequest = MockServerHttpRequest.get("/oauth2/authorization/id").header("X-Forwarded-Host", "evil.com");
ServerWebExchange exchange = MockServerWebExchange.from(httpRequest);
OAuth2AuthorizationRequest request = this.resolver.resolve(exchange).block();
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_3
Test Case Name: resolveWhenAuthorizationRequestWithValidPublicClientThenResolves(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenAuthorizationRequestWithValidPublicClientThenResolves() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build()));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(
+ Mono.just(TestClientRegistrations.clientRegistration().clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build())
+ );
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(PkceParameterNames.CODE_VERIFIER)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&" + "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
@@
Original Test Code (click to expand)
@Test
public void resolveWhenAuthorizationRequestWithValidPublicClientThenResolves() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().clientAuthenticationMethod(ClientAuthenticationMethod.NONE).clientSecret(null).build()));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(PkceParameterNames.CODE_VERIFIER)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&" + "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_4
Test Case Name: resolveWhenRequireProofKeyTrueThenPkceEnabled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ClientRegistration.ClientSettings pkceEnabled = ClientRegistration.ClientSettings.builder().requireProofKey(true).build();
ClientRegistration clientWithPkceEnabled = TestClientRegistrations.clientRegistration().clientSettings(pkceEnabled).build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientWithPkceEnabled));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(clientWithPkceEnabled));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/" + clientWithPkceEnabled.getRegistrationId());
assertPkceApplied(request, clientWithPkceEnabled);
}
Original Test Code (click to expand)
@Test
void resolveWhenRequireProofKeyTrueThenPkceEnabled() {
ClientRegistration.ClientSettings pkceEnabled = ClientRegistration.ClientSettings.builder().requireProofKey(true).build();
ClientRegistration clientWithPkceEnabled = TestClientRegistrations.clientRegistration().clientSettings(pkceEnabled).build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientWithPkceEnabled));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/" + clientWithPkceEnabled.getRegistrationId());
assertPkceApplied(request, clientWithPkceEnabled);
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_5
Test Case Name: resolveWhenAuthenticationRequestWithValidOidcClientThenResolves(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(
+ Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())
+ );
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(OidcParameterNames.NONCE)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}");
}
@@
Original Test Code (click to expand)
@Test
public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
OAuth2AuthorizationRequest request = resolve("/oauth2/authorization/registration-id");
assertThat((String) request.getAttribute(OidcParameterNames.NONCE)).matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(request.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.*?&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_6
Test Case Name: resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(
+ Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())
+ );
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE)).attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).containsKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE)).attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).containsKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_7
Test Case Name: resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(
+ Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())
+ );
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.authorizationRequestUri((uriBuilder) -> {
uriBuilder.queryParam("param1", "value1");
return uriBuilder.build();
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "param1=value1");
}
@@
Original Test Code (click to expand)
@Test
public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.authorizationRequestUri((uriBuilder) -> {
uriBuilder.queryParam("param1", "value1");
return uriBuilder.build();
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "param1=value1");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_8
Test Case Name: resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(
+ Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build())
+ );
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.parameters((params) -> {
params.put("appid", params.get("client_id"));
params.remove("client_id");
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "appid=client-id");
}
@@
Original Test Code (click to expand)
@Test
public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().scope(OidcScopes.OPENID).build()));
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.parameters((params) -> {
params.put("appid", params.get("client_id"));
params.remove("client_id");
}));
OAuth2AuthorizationRequest authorizationRequest = resolve("/oauth2/authorization/registration-id");
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "scope=openid&state=.{15,}&" + "redirect_uri=/login/oauth2/code/registration-id&" + "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "appid=client-id");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_9
Test Case Name: filterWhenMatchThenAuthorizedClientSaved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationCodeGrantWebFilterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
Original Test Code (click to expand)
@Test
public void filterWhenMatchThenAuthorizedClientSaved() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(AnonymousAuthenticationToken.class), any());
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_10
Test Case Name: filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationCodeGrantWebFilterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
public void filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
// 1) redirect_uri with query parameters
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback", parameters);
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(1)).authenticate(any());
// 2) redirect_uri with query parameters AND authorization response additional
// parameters
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(2)).authenticate(any());
}
@@
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback", parameters);
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(1)).authenticate(any());
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
exchange = MockServerWebExchange.from(authorizationResponse);
this.filter.filter(exchange, chain).block();
verify(this.authenticationManager, times(2)).authenticate(any());
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_11
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
ServerRequestCache requestCache = mock(ServerRequestCache.class);
given(requestCache.getRedirectUri(any(ServerWebExchange.class))).willReturn(Mono.just(URI.create("/saved-request")));
this.filter.setRequestCache(requestCache);
this.filter.filter(exchange, chain).block();
verify(requestCache).getRedirectUri(exchange);
assertThat(exchange.getResponse().getHeaders().getLocation().toString()).isEqualTo("/saved-request");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_12
Test Case Name: filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationCodeGrantWebFilterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.filter.filter(exchange, chain).block()).satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_13
Test Case Name: applyWhenCodeParameterNotFoundThenErrorCode(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
this.request.queryParam(OAuth2ParameterNames.ERROR, "error");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(this.clientRegistration));
assertThat(applyConverter().getAuthorizationExchange().getAuthorizationResponse().getError().getErrorCode()).isEqualTo("error");
}
Original Test Code (click to expand)
@Test
public void applyWhenCodeParameterNotFoundThenErrorCode() {
this.request.queryParam(OAuth2ParameterNames.ERROR, "error");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.clientRegistration));
assertThat(applyConverter().getAuthorizationExchange().getAuthorizationResponse().getError().getErrorCode()).isEqualTo("error");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Test Case ID #spring-security_Test_167_14
Test Case Name: applyWhenCodeParameterFoundThenCode(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
this.request.queryParam(OAuth2ParameterNames.CODE, "code");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.clientRegistration));
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository(Mono.just(this.clientRegistration));
OAuth2AuthorizationCodeAuthenticationToken result = applyConverter();
OAuth2AuthorizationResponse exchange = result.getAuthorizationExchange().getAuthorizationResponse();
assertThat(exchange.getError()).isNull();
assertThat(exchange.getCode()).isEqualTo("code");
Original Test Code (click to expand)
@Test
public void applyWhenCodeParameterFoundThenCode() {
this.request.queryParam(OAuth2ParameterNames.CODE, "code");
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizationCodeAuthenticationToken result = applyConverter();
OAuth2AuthorizationResponse exchange = result.getAuthorizationExchange().getAuthorizationResponse();
assertThat(exchange.getError()).isNull();
assertThat(exchange.getCode()).isEqualTo("code");
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository(Mono<ClientRegistration> registrationMono) {
ReactiveClientRegistrationRepository mock = mock(ReactiveClientRegistrationRepository.class);
given(mock.findByRegistrationId(any())).willReturn(registrationMono);
return mock;
}
}
Mock Clone Instance #spring-security_MCI_168
- Scope: class level
- Mocked Class:
org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository
- Test Case Count: 3
- MO Count: 3
Reusable Method
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository mockRepository = mock(ReactiveClientRegistrationRepository.class);
given(mockRepository.findByRegistrationId(any())).willReturn(Mono.empty());
return mockRepository;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_168_1
Test Case Name: resolveWhenClientRegistrationNotFoundMatchThenBadRequest(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\DefaultServerOAuth2AuthorizationRequestResolverTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
@Test
public void resolveWhenClientRegistrationNotFoundMatchThenBadRequest() {
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository();
assertThatExceptionOfType(ResponseStatusException.class).isThrownBy(() -> resolve("/oauth2/authorization/not-found-id")).satisfies((ex) -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
Original Test Code (click to expand)
@Test
public void resolveWhenClientRegistrationNotFoundMatchThenBadRequest() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
assertThatExceptionOfType(ResponseStatusException.class).isThrownBy(() -> resolve("/oauth2/authorization/not-found-id")).satisfies((ex) -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository mockRepository = mock(ReactiveClientRegistrationRepository.class);
given(mockRepository.findByRegistrationId(any())).willReturn(Mono.empty());
return mockRepository;
}
}
Test Case ID #spring-security_Test_168_2
Test Case Name: applyWhenClientRegistrationMissingThenOAuth2AuthorizationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\ServerOAuth2AuthorizationCodeAuthenticationTokenConverterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository();
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter()).withMessageContaining(ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
}
Original Test Code (click to expand)
@Test
public void applyWhenClientRegistrationMissingThenOAuth2AuthorizationException() {
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(this.authorizationRequest.build()));
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> applyConverter()).withMessageContaining(ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository mockRepository = mock(ReactiveClientRegistrationRepository.class);
given(mockRepository.findByRegistrationId(any())).willReturn(Mono.empty());
return mockRepository;
}
}
Test Case ID #spring-security_Test_168_3
Test Case Name: filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\server\OAuth2AuthorizationCodeGrantWebFilterTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
- given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
+ this.clientRegistrationRepository = MockReactiveClientRegistrationRepository.createMockReactiveClientRegistrationRepository();
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationConverterThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.filter.filter(exchange, chain).block()).satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("client_registration_not_found"));
verifyNoInteractions(this.authenticationManager);
}
Reusable Method for MCI (click to expand)
public class MockReactiveClientRegistrationRepository {
public static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository mockRepository = mock(ReactiveClientRegistrationRepository.class);
given(mockRepository.findByRegistrationId(any())).willReturn(Mono.empty());
return mockRepository;
}
}
Mock Clone Instance #spring-security_MCI_169
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
return clientRegistrationRepository;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_169_1
Test Case Name: shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Login(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
public void shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Login() {
- ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
- given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
+ ReactiveClientRegistrationRepository clientRegistrationRepository = createMockReactiveClientRegistrationRepository();
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange().expectStatus().is3xxRedirection();
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isInstanceOf(DefaultServerRedirectStrategy.class);
}
Original Test Code (click to expand)
@Test
public void shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Login() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange().expectStatus().is3xxRedirection();
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isInstanceOf(DefaultServerRedirectStrategy.class);
}
Reusable Method for MCI (click to expand)
private static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
return clientRegistrationRepository;
}
Test Case ID #spring-security_Test_169_2
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
- ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
- given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
+ ReactiveClientRegistrationRepository clientRegistrationRepository = createMockReactiveClientRegistrationRepository();
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
@@
Original Test Code (click to expand)
@Test
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Login() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
Reusable Method for MCI (click to expand)
private static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
return clientRegistrationRepository;
}
Test Case ID #spring-security_Test_169_3
Test Case Name: shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Client(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\web\server\ServerHttpSecurityTests.java)
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
public void shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Client() {
- ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
- given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
+ ReactiveClientRegistrationRepository clientRegistrationRepository = createMockReactiveClientRegistrationRepository();
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange().expectStatus().is3xxRedirection();
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isInstanceOf(DefaultServerRedirectStrategy.class);
}
Original Test Code (click to expand)
@Test
public void shouldUseDefaultAuthorizationRedirectStrategyForOAuth2Client() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange().expectStatus().is3xxRedirection();
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isInstanceOf(DefaultServerRedirectStrategy.class);
}
Reusable Method for MCI (click to expand)
private static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
return clientRegistrationRepository;
}
Test Case ID #spring-security_Test_169_4
Mock Object Variable Name: clientRegistrationRepository
Suggested Diff
@@
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
- ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
- given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
+ ReactiveClientRegistrationRepository clientRegistrationRepository = createMockReactiveClientRegistrationRepository();
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
@@
Original Test Code (click to expand)
@Test
public void shouldConfigureAuthorizationRedirectStrategyForOAuth2Client() {
ServerRedirectStrategy authorizationRedirectStrategy = mock(ServerRedirectStrategy.class);
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
given(authorizationRedirectStrategy.sendRedirect(any(), any())).willReturn(Mono.empty());
SecurityWebFilterChain securityFilterChain = this.http.oauth2Client().clientRegistrationRepository(clientRegistrationRepository).authorizationRedirectStrategy(authorizationRedirectStrategy).and().build();
WebTestClient client = WebTestClientBuilder.bindToWebFilters(securityFilterChain).build();
client.get().uri("/oauth2/authorization/registration-id").exchange();
verify(authorizationRedirectStrategy).sendRedirect(any(), any());
OAuth2AuthorizationRequestRedirectWebFilter filter = getWebFilter(securityFilterChain, OAuth2AuthorizationRequestRedirectWebFilter.class).get();
assertThat(ReflectionTestUtils.getField(filter, "authorizationRedirectStrategy")).isSameAs(authorizationRedirectStrategy);
}
Reusable Method for MCI (click to expand)
private static ReactiveClientRegistrationRepository createMockReactiveClientRegistrationRepository() {
ReactiveClientRegistrationRepository clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(TestClientRegistrations.clientRegistration().build()));
return clientRegistrationRepository;
}
Mock Clone Instance #spring-security_MCI_170
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.server.resource.web.BearerTokenResolver
- Test Case Count: 2
- MO Count: 2
Reusable Method
private BearerTokenResolver resolverBean;
private BearerTokenResolver resolver;
@BeforeEach
public void setUp() {
resolverBean = mock(BearerTokenResolver.class);
resolver = mock(BearerTokenResolver.class);
}
resolverBean;
resolver;
The refactoring details in each test cases
Test Case ID #spring-security_Test_170_1
Mock Object Variable Name: resolverBean
Suggested Diff
@@
+ // Cannot refactor mock `resolverBean`: ambiguous new variable name provided
Original Test Code (click to expand)
@Test
public void getBearerTokenResolverWhenDuplicateResolverBeansAndAnotherOnTheDslThenTheDslOneIsUsed() {
BearerTokenResolver resolverBean = mock(BearerTokenResolver.class);
BearerTokenResolver resolver = mock(BearerTokenResolver.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean("resolverOne", BearerTokenResolver.class, () -> resolverBean);
context.registerBean("resolverTwo", BearerTokenResolver.class, () -> resolverBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.bearerTokenResolver(resolver);
assertThat(oauth2.getBearerTokenResolver()).isEqualTo(resolver);
}
Reusable Method for MCI (click to expand)
private BearerTokenResolver resolverBean;
private BearerTokenResolver resolver;
@BeforeEach
public void setUp() {
resolverBean = mock(BearerTokenResolver.class);
resolver = mock(BearerTokenResolver.class);
}
resolverBean;
resolver;
Test Case ID #spring-security_Test_170_2
Mock Object Variable Name: resolver
Suggested Diff
@@
+ // Cannot refactor mock `resolver`: ambiguous mapping for new variable name
Original Test Code (click to expand)
@Test
public void getBearerTokenResolverWhenResolverBeanAndAnotherOnTheDslThenTheDslOneIsUsed() {
BearerTokenResolver resolver = mock(BearerTokenResolver.class);
BearerTokenResolver resolverBean = mock(BearerTokenResolver.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(BearerTokenResolver.class, () -> resolverBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer oauth2 = new OAuth2ResourceServerConfigurer(context);
oauth2.bearerTokenResolver(resolver);
assertThat(oauth2.getBearerTokenResolver()).isEqualTo(resolver);
}
Reusable Method for MCI (click to expand)
private BearerTokenResolver resolverBean;
private BearerTokenResolver resolver;
@BeforeEach
public void setUp() {
resolverBean = mock(BearerTokenResolver.class);
resolver = mock(BearerTokenResolver.class);
}
resolverBean;
resolver;
Mock Clone Instance #spring-security_MCI_171
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.core.OAuth2TokenValidator<org.springframework.security.oauth2.core.OAuth2Token>
- Test Case Count: 4
- MO Count: 8
Reusable Method
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_171_1
Test Case Name: validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: success
Suggested Diff
@@
@Test
public void validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator() {
- OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class);
+ OAuth2TokenValidator<OAuth2Token> success = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.success());
OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class);
- given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
}
@@
Original Test Code (click to expand)
@Test
public void validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator() {
OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class);
given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_2
Test Case Name: validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: failure
Suggested Diff
@@
OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class);
- OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class);
- given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
- given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
+ OAuth2TokenValidator<OAuth2Token> failure = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.failure(DETAIL));
+ given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
@@
Original Test Code (click to expand)
@Test
public void validateWhenAnyValidatorFailsThenReturnsFailureResultContainingDetailFromFailingValidator() {
OAuth2TokenValidator<OAuth2Token> success = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> failure = mock(OAuth2TokenValidator.class);
given(success.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(failure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(success, failure));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_3
Test Case Name: validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: firstFailure
Suggested Diff
@@
@Test
public void validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails() {
- OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class);
OAuth2Error otherDetail = new OAuth2Error("another-error");
- given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
+ OAuth2TokenValidator<OAuth2Token> firstFailure = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.failure(DETAIL));
given(secondFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(otherDetail));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
}
@@
Original Test Code (click to expand)
@Test
public void validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails() {
OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class);
OAuth2Error otherDetail = new OAuth2Error("another-error");
given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
given(secondFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(otherDetail));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_4
Test Case Name: validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-core\src\test\java\org\springframework\security\oauth2\core\DelegatingOAuth2TokenValidatorTests.java)
Mock Object Variable Name: secondFailure
Suggested Diff
@@
OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class);
- OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class);
OAuth2Error otherDetail = new OAuth2Error("another-error");
given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
- given(secondFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(otherDetail));
+ OAuth2TokenValidator<OAuth2Token> secondFailure = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.failure(otherDetail));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
@@
Original Test Code (click to expand)
@Test
public void validateWhenMultipleValidatorsFailThenReturnsFailureResultContainingAllDetails() {
OAuth2TokenValidator<OAuth2Token> firstFailure = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondFailure = mock(OAuth2TokenValidator.class);
OAuth2Error otherDetail = new OAuth2Error("another-error");
given(firstFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(DETAIL));
given(secondFailure.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.failure(otherDetail));
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(firstFailure, secondFailure);
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors()).containsExactly(DETAIL, otherDetail);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_5
Mock Object Variable Name: firstSuccess
Suggested Diff
@@
@Test
public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() {
- OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
- given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
+ OAuth2TokenValidator<OAuth2Token> firstSuccess = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
}
@@
Original Test Code (click to expand)
@Test
public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_6
Mock Object Variable Name: secondSuccess
Suggested Diff
@@
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
- OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
- given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
+ OAuth2TokenValidator<OAuth2Token> secondSuccess = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
@@
Original Test Code (click to expand)
@Test
public void validateWhenAllValidatorsSucceedThenReturnsSuccessfulResult() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> tokenValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
OAuth2Token token = mock(OAuth2Token.class);
OAuth2TokenValidatorResult result = tokenValidator.validate(token);
assertThat(result.hasErrors()).isFalse();
assertThat(result.getErrors()).isEmpty();
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_7
Mock Object Variable Name: firstSuccess
Suggested Diff
@@
public void constructorsWhenInvokedWithSameInputsThenResultInSameOutputs() {
- OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
+ OAuth2TokenValidator<OAuth2Token> firstSuccess = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.success());
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
- given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess);
OAuth2Token token = mock(OAuth2Token.class);
firstValidator.validate(token);
secondValidator.validate(token);
verify(firstSuccess, times(2)).validate(token);
verify(secondSuccess, times(2)).validate(token);
@@
Original Test Code (click to expand)
@Test
public void constructorsWhenInvokedWithSameInputsThenResultInSameOutputs() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess);
OAuth2Token token = mock(OAuth2Token.class);
firstValidator.validate(token);
secondValidator.validate(token);
verify(firstSuccess, times(2)).validate(token);
verify(secondSuccess, times(2)).validate(token);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Test Case ID #spring-security_Test_171_8
Mock Object Variable Name: secondSuccess
Suggested Diff
@@
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
- OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
- given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
- given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
+ given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
+ OAuth2TokenValidator<OAuth2Token> secondSuccess = createMockOAuth2TokenValidator(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
@@
Original Test Code (click to expand)
@Test
public void constructorsWhenInvokedWithSameInputsThenResultInSameOutputs() {
OAuth2TokenValidator<OAuth2Token> firstSuccess = mock(OAuth2TokenValidator.class);
OAuth2TokenValidator<OAuth2Token> secondSuccess = mock(OAuth2TokenValidator.class);
given(firstSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
given(secondSuccess.validate(any(OAuth2Token.class))).willReturn(OAuth2TokenValidatorResult.success());
DelegatingOAuth2TokenValidator<OAuth2Token> firstValidator = new DelegatingOAuth2TokenValidator<>(Arrays.asList(firstSuccess, secondSuccess));
DelegatingOAuth2TokenValidator<OAuth2Token> secondValidator = new DelegatingOAuth2TokenValidator<>(firstSuccess, secondSuccess);
OAuth2Token token = mock(OAuth2Token.class);
firstValidator.validate(token);
secondValidator.validate(token);
verify(firstSuccess, times(2)).validate(token);
verify(secondSuccess, times(2)).validate(token);
}
Reusable Method for MCI (click to expand)
private static OAuth2TokenValidator<OAuth2Token> createMockOAuth2TokenValidator(OAuth2TokenValidatorResult validateReturn) {
OAuth2TokenValidator<OAuth2Token> mockValidator = mock(OAuth2TokenValidator.class);
given(mockValidator.validate(any(OAuth2Token.class))).willReturn(validateReturn);
return mockValidator;
}
Mock Clone Instance #spring-security_MCI_172
- Scope: method level
- Mocked Class:
org.springframework.security.authentication.jaas.JaasAuthenticationToken
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static JaasAuthenticationToken createMockJaasAuthenticationToken(LoginContext loginContext) {
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
given(token.getLoginContext()).willReturn(loginContext);
return token;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_172_1
Test Case Name: logout(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: token
Suggested Diff
@@
SecurityContext securityContext = mock(SecurityContext.class);
- JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
+ JaasAuthenticationToken token = createMockJaasAuthenticationToken(context);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
- given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
@@
Original Test Code (click to expand)
@Test
public void logout() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static JaasAuthenticationToken createMockJaasAuthenticationToken(LoginContext loginContext) {
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
given(token.getLoginContext()).willReturn(loginContext);
return token;
}
Test Case ID #spring-security_Test_172_2
Test Case Name: logoutLoginException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\jaas\DefaultJaasAuthenticationProviderTests.java)
Mock Object Variable Name: token
Suggested Diff
@@
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
- JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
+ JaasAuthenticationToken token = createMockJaasAuthenticationToken(context);
given(securityContext.getAuthentication()).willReturn(token);
- given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
@@
Original Test Code (click to expand)
@Test
public void logoutLoginException() throws Exception {
SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
SecurityContext securityContext = mock(SecurityContext.class);
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
LoginContext context = mock(LoginContext.class);
LoginException loginException = new LoginException("Failed Login");
given(event.getSecurityContexts()).willReturn(Arrays.asList(securityContext));
given(securityContext.getAuthentication()).willReturn(token);
given(token.getLoginContext()).willReturn(context);
willThrow(loginException).given(context).logout();
this.provider.onApplicationEvent(event);
verify(event).getSecurityContexts();
verify(securityContext).getAuthentication();
verify(token).getLoginContext();
verify(context).logout();
verify(this.log).warn(anyString(), eq(loginException));
verifyNoMoreInteractions(event, securityContext, token, context);
}
Reusable Method for MCI (click to expand)
private static JaasAuthenticationToken createMockJaasAuthenticationToken(LoginContext loginContext) {
JaasAuthenticationToken token = mock(JaasAuthenticationToken.class);
given(token.getLoginContext()).willReturn(loginContext);
return token;
}
Mock Clone Instance #spring-security_MCI_173
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.TokenExchangeGrantRequest, org.springframework.util.MultiValueMap<java.lang.String, java.lang.String>>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockParametersConverter {
public static Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(TokenExchangeGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
return parametersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_173_1
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(TokenExchangeGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_173_2
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\RestClientTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()), param(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SUBJECT_TOKEN, this.subjectToken.getTokenValue()), param(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
Set<String> scopes = clientRegistration.getScopes();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()), param(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SUBJECT_TOKEN, this.subjectToken.getTokenValue()), param(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " ")), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(TokenExchangeGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_173_3
Test Case Name: getTokenResponseWhenParametersConverterSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
+ Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("custom-parameter-name=custom-parameter-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.setParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("custom-parameter-name=custom-parameter-value");
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(TokenExchangeGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
return parametersConverter;
}
}
Test Case ID #spring-security_Test_173_4
Test Case Name: getTokenResponseWhenParametersConverterAddedThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\endpoint\WebClientReactiveTokenExchangeTokenResponseClientTests.java)
Mock Object Variable Name: parametersConverter
Suggested Diff
@@
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
- given(parametersConverter.convert(grantRequest)).willReturn(parameters);
+ Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = MockParametersConverter.createMockParametersConverter(grantRequest, parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()), param(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SUBJECT_TOKEN, this.subjectToken.getTokenValue()), param(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.clientRegistration.build().getScopes(), " ")), param("custom-parameter-name", "custom-parameter-value"));
// @formatter:on
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenParametersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add("custom-parameter-name", "custom-parameter-value");
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
this.tokenResponseClient.addParametersConverter(parametersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(parametersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains(param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()), param(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SUBJECT_TOKEN, this.subjectToken.getTokenValue()), param(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE), param(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.clientRegistration.build().getScopes(), " ")), param("custom-parameter-name", "custom-parameter-value"));
}
Reusable Method for MCI (click to expand)
public class MockParametersConverter {
public static Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> createMockParametersConverter(TokenExchangeGrantRequest grantRequest, MultiValueMap<String, String> parameters) {
Converter<TokenExchangeGrantRequest, MultiValueMap<String, String>> parametersConverter = mock();
given(parametersConverter.convert(grantRequest)).willReturn(parameters);
return parametersConverter;
}
}
Mock Clone Instance #spring-security_MCI_174
- Scope: class level
- Mocked Class:
org.springframework.security.web.server.header.ServerHttpHeadersWriter
- Test Case Count: 4
- MO Count: 5
Reusable Method
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_174_1
Mock Object Variable Name: writer1
Suggested Diff
@@
@Test
public void writeHttpHeadersWhenErrorNoErrorThenError() {
- given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
+ this.writer1 = MockServerHttpHeadersWriter.createMockServerHttpHeadersWriter(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
}
Original Test Code (click to expand)
@Test
public void writeHttpHeadersWhenErrorNoErrorThenError() {
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
Test Case ID #spring-security_Test_174_2
Mock Object Variable Name: writer1
Suggested Diff
@@
@Test
public void writeHttpHeadersWhenErrorErrorThenError() {
- given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
+ this.writer1 = MockServerHttpHeadersWriter.createMockServerHttpHeadersWriter(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
}
Original Test Code (click to expand)
@Test
public void writeHttpHeadersWhenErrorErrorThenError() {
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.error(new RuntimeException()));
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
Test Case ID #spring-security_Test_174_3
Mock Object Variable Name: writer1
Suggested Diff
@@
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
- given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
+ this.writer1 = MockServerHttpHeadersWriter.createMockServerHttpHeadersWriter(Mono.empty());
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectComplete().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
verify(this.writer2).writeHttpHeaders(this.exchange);
}
Original Test Code (click to expand)
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectComplete().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
verify(this.writer2).writeHttpHeaders(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
Test Case ID #spring-security_Test_174_4
Mock Object Variable Name: writer2
Suggested Diff
@@
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
- given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
+ this.writer2 = MockServerHttpHeadersWriter.createMockServerHttpHeadersWriter(Mono.empty());
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectComplete().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
verify(this.writer2).writeHttpHeaders(this.exchange);
}
Original Test Code (click to expand)
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
given(this.writer1.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
given(this.writer2.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectComplete().verify();
verify(this.writer1).writeHttpHeaders(this.exchange);
verify(this.writer2).writeHttpHeaders(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
Test Case ID #spring-security_Test_174_5
Mock Object Variable Name: delegate
Suggested Diff
@@
given(this.matcher.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(Collections.emptyMap()));
- given(this.delegate.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
+ this.delegate = MockServerHttpHeadersWriter.createMockServerHttpHeadersWriter(Mono.empty());
this.headerWriter.writeHttpHeaders(this.exchange).block();
verify(this.delegate).writeHttpHeaders(this.exchange);
Original Test Code (click to expand)
@Test
public void writeHeadersWhenMatchThenDelegateWriteHttpHeaders() {
given(this.matcher.matches(this.exchange)).willReturn(ServerWebExchangeMatcher.MatchResult.match(Collections.emptyMap()));
given(this.delegate.writeHttpHeaders(this.exchange)).willReturn(Mono.empty());
this.headerWriter.writeHttpHeaders(this.exchange).block();
verify(this.delegate).writeHttpHeaders(this.exchange);
}
Reusable Method for MCI (click to expand)
public class MockServerHttpHeadersWriter {
public static ServerHttpHeadersWriter createMockServerHttpHeadersWriter(Mono<Void> writeHttpHeadersReturn) {
ServerHttpHeadersWriter mockWriter = mock(ServerHttpHeadersWriter.class);
given(mockWriter.writeHttpHeaders(any(ServerWebExchange.class))).willReturn(writeHttpHeadersReturn);
return mockWriter;
}
}
Mock Clone Instance #spring-security_MCI_175
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static FilterChain createMockFilterChain(ClientAuthorizationRequiredException exception) throws Exception {
FilterChain filterChain = mock(FilterChain.class);
willThrow(exception).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
return filterChain;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_175_1
Test Case Name: doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenRedirectForAuthorization(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
- willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ FilterChain filterChain = createMockFilterChain(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId()));
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/authorize/oauth2/code/registration-id");
verify(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenRedirectForAuthorization() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/authorize/oauth2/code/registration-id");
verify(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private static FilterChain createMockFilterChain(ClientAuthorizationRequiredException exception) throws Exception {
FilterChain filterChain = mock(FilterChain.class);
willThrow(exception).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
return filterChain;
}
Test Case ID #spring-security_Test_175_2
Test Case Name: doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownButAuthorizationRequestNotResolvedThenStatusInternalServerError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
- willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ FilterChain filterChain = createMockFilterChain(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId()));
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownButAuthorizationRequestNotResolvedThenStatusInternalServerError() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
Reusable Method for MCI (click to expand)
private static FilterChain createMockFilterChain(ClientAuthorizationRequiredException exception) throws Exception {
FilterChain filterChain = mock(FilterChain.class);
willThrow(exception).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
return filterChain;
}
Test Case ID #spring-security_Test_175_3
Test Case Name: doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenSaveRequestBeforeCommitted(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ FilterChain filterChain = createMockFilterChain(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId()));
willAnswer((invocation) -> assertThat((invocation.<HttpServletResponse>getArgument(1)).isCommitted()).isFalse()).given(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
- willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
assertThat(response.isCommitted()).isTrue();
@@
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenSaveRequestBeforeCommitted() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willAnswer((invocation) -> assertThat((invocation.<HttpServletResponse>getArgument(1)).isCommitted()).isFalse()).given(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
assertThat(response.isCommitted()).isTrue();
}
Reusable Method for MCI (click to expand)
private static FilterChain createMockFilterChain(ClientAuthorizationRequiredException exception) throws Exception {
FilterChain filterChain = mock(FilterChain.class);
willThrow(exception).given(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
return filterChain;
}
Mock Clone Instance #spring-security_MCI_176
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 9
- MO Count: 9
Reusable Method
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
The refactoring details in each test cases
Test Case ID #spring-security_Test_176_1
Test Case Name: doFilterWhenNotAuthorizationRequestThenNextFilter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_2
Test Case Name: doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_3
Test Case Name: doFilterWhenAuthorizationRequestWithInvalidClientAndCustomFailureHandlerThenCustomError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientAndCustomFailureHandlerThenCustomError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.setAuthenticationFailureHandler((request1, response1, ex) -> {
Throwable cause = ex.getCause();
if (InvalidClientRegistrationIdException.class.isAssignableFrom(cause.getClass())) {
response1.sendError(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase());
} else {
response1.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
});
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase());
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientAndCustomFailureHandlerThenCustomError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.setAuthenticationFailureHandler((request1, response1, ex) -> {
Throwable cause = ex.getCause();
if (InvalidClientRegistrationIdException.class.isAssignableFrom(cause.getClass())) {
response1.sendError(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase());
} else {
response1.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
});
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase());
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_4
Test Case Name: doFilterWhenAuthorizationRequestOAuth2LoginThenRedirectForAuthorization(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenRedirectForAuthorization() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenRedirectForAuthorization() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_5
Test Case Name: doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(AuthorizationRequestRepository.class);
this.filter.setAuthorizationRequestRepository(authorizationRequestRepository);
- this.filter.doFilter(request, response, filterChain);
+ this.filter.doFilter(request, response, filterChain);
- verifyNoMoreInteractions(filterChain);
+ verifyNoMoreInteractions(filterChain);
verify(authorizationRequestRepository).saveAuthorizationRequest(any(OAuth2AuthorizationRequest.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration2.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(AuthorizationRequestRepository.class);
this.filter.setAuthorizationRequestRepository(authorizationRequestRepository);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(authorizationRequestRepository).saveAuthorizationRequest(any(OAuth2AuthorizationRequest.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_6
Test Case Name: doFilterWhenCustomAuthorizationRequestBaseUriThenRedirectForAuthorization(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenCustomAuthorizationRequestBaseUriThenRedirectForAuthorization() throws Exception {
String authorizationRequestBaseUri = "/custom/authorization";
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, authorizationRequestBaseUri);
String requestUri = authorizationRequestBaseUri + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomAuthorizationRequestBaseUriThenRedirectForAuthorization() throws Exception {
String authorizationRequestBaseUri = "/custom/authorization";
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, authorizationRequestBaseUri);
String requestUri = authorizationRequestBaseUri + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_7
Test Case Name: doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
request.addParameter("idp", "https://other.provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
@@
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
- filter.doFilter(request, response, filterChain);
+ filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "idp=https://other.provider.com");
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter("idp", "https://other.provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "idp=https://other.provider.com");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_8
Test Case Name: doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
@@
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
- filter.doFilter(request, response, filterChain);
+ filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "login_hint=user@provider\\.com");
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
String loginHintParamName = "login_hint";
request.addParameter(loginHintParamName, "user@provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest defaultAuthorizationRequest = defaultAuthorizationRequestResolver.resolve(request);
Map<String, Object> additionalParameters = new HashMap<>(defaultAuthorizationRequest.getAdditionalParameters());
additionalParameters.put(loginHintParamName, request.getParameter(loginHintParamName));
String customAuthorizationRequestUri = UriComponentsBuilder.fromUriString(defaultAuthorizationRequest.getAuthorizationRequestUri()).queryParam(loginHintParamName, additionalParameters.get(loginHintParamName)).build(true).toUriString();
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.from(defaultAuthorizationRequestResolver.resolve(request)).additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).authorizationRequestUri(customAuthorizationRequestUri).build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id&" + "login_hint=user@provider\\.com");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_176_9
Test Case Name: doFilterWhenCustomAuthorizationRedirectStrategySetThenCustomAuthorizationRedirectStrategyUsed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenCustomAuthorizationRedirectStrategySetThenCustomAuthorizationRedirectStrategyUsed() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
RedirectStrategy customRedirectStrategy = (httpRequest, httpResponse, url) -> {
String redirectUrl = httpResponse.encodeRedirectURL(url);
httpResponse.setStatus(HttpStatus.OK.value());
httpResponse.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
httpResponse.getWriter().write(redirectUrl);
httpResponse.getWriter().flush();
};
this.filter.setAuthorizationRedirectStrategy(customRedirectStrategy);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(response.getContentAsString(StandardCharsets.UTF_8)).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomAuthorizationRedirectStrategySetThenCustomAuthorizationRedirectStrategyUsed() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
RedirectStrategy customRedirectStrategy = (httpRequest, httpResponse, url) -> {
String redirectUrl = httpResponse.encodeRedirectURL(url);
httpResponse.setStatus(HttpStatus.OK.value());
httpResponse.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
httpResponse.getWriter().write(redirectUrl);
httpResponse.getWriter().flush();
};
this.filter.setAuthorizationRedirectStrategy(customRedirectStrategy);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(response.getContentAsString(StandardCharsets.UTF_8)).matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&" + "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Mock Clone Instance #spring-security_MCI_177
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 14
- MO Count: 14
Reusable Method
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
The refactoring details in each test cases
Test Case ID #spring-security_Test_177_1
Test Case Name: doFilterWhenNotAuthorizationResponseThenNotProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenNotAuthorizationResponseThenNotProcessed() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
// NOTE: A valid Authorization Response contains either a 'code' or 'error'
// parameter.
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationResponseThenNotProcessed() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_2
Test Case Name: doFilterWhenAuthorizationRequestNotFoundThenNotProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationRequestNotFoundThenNotProcessed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/path");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestNotFoundThenNotProcessed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/path");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_3
Test Case Name: doFilterWhenAuthorizationRequestRedirectUriDoesNotMatchThenNotProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse.setRequestURI(requestUri + "-no-match");
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(authorizationResponse, response, filterChain);
@@
- verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestRedirectUriDoesNotMatchThenNotProcessed() throws Exception {
String requestUri = "/callback/client-1";
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri);
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse.setRequestURI(requestUri + "-no-match");
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_4
Test Case Name: doFilterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
this.setUpAuthenticationResult(this.registration1);
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
// 2) redirect_uri with query parameters AND authorization response additional
// parameters
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() throws Exception {
String requestUri = "/callback/client-1";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_5
Test Case Name: doFilterWhenAuthorizationRequestRedirectUriParametersDoesNotMatchThenNotProcessed(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
this.setUpAuthenticationResult(this.registration1);
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
// 1) Parameter value
Map<String, String> parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.put("param2", "value8");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
- this.filter.doFilter(authorizationResponse, response, filterChain);
+ this.filter.doFilter(authorizationResponse, response, filterChain);
- verify(filterChain, times(1)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(filterChain, times(1)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// 2) Parameter order
parametersNotMatch = new LinkedHashMap<>();
parametersNotMatch.put("param2", "value2");
parametersNotMatch.put("param1", "value1");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
- this.filter.doFilter(authorizationResponse, response, filterChain);
+ this.filter.doFilter(authorizationResponse, response, filterChain);
- verify(filterChain, times(2)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(filterChain, times(2)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// 3) Parameter missing
parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.remove("param2");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
- this.filter.doFilter(authorizationResponse, response, filterChain);
+ this.filter.doFilter(authorizationResponse, response, filterChain);
- verify(filterChain, times(3)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(filterChain, times(3)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestRedirectUriParametersDoesNotMatchThenNotProcessed() throws Exception {
String requestUri = "/callback/client-1";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
FilterChain filterChain = mock(FilterChain.class);
Map<String, String> parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.put("param2", "value8");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(1)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
parametersNotMatch = new LinkedHashMap<>();
parametersNotMatch.put("param2", "value2");
parametersNotMatch.put("param1", "value1");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(2)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.remove("param2");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(3)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_6
Test Case Name: doFilterWhenAuthorizationRequestMatchThenAuthorizationRequestRemoved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationRequestMatchThenAuthorizationRequestRemoved() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(authorizationResponse)).isNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationRequestMatchThenAuthorizationRequestRemoved() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(authorizationResponse)).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_7
Test Case Name: doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT);
given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(new OAuth2AuthorizationException(error));
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1?error=invalid_grant");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT);
given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(new OAuth2AuthorizationException(error));
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1?error=invalid_grant");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_8
Test Case Name: doFilterWhenAuthorizationSucceedsThenAuthorizedClientSavedToService(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationSucceedsThenAuthorizedClientSavedToService() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsThenAuthorizedClientSavedToService() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_9
Test Case Name: doFilterWhenAuthorizationSucceedsThenRedirected(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationSucceedsThenRedirected() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsThenRedirected() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_10
Test Case Name: doFilterWhenCustomSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password")));
this.filter.setSecurityContextHolderStrategy(strategy);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(strategy).getContext();
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password")));
this.filter.setSecurityContextHolderStrategy(strategy);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(strategy).getContext();
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_11
Test Case Name: doFilterWhenAuthorizationSucceedsAndHasSavedRequestThenRedirectToSavedRequest(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
request.addParameter(OAuth2ParameterNames.CODE, "code");
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
String redirectUrl = requestCache.getRequest(request, response).getRedirectUrl();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsAndHasSavedRequestThenRedirectToSavedRequest() throws Exception {
String requestUri = "/saved-request";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
RequestCache requestCache = new HttpSessionRequestCache();
requestCache.saveRequest(request, response);
request.setRequestURI("/callback/client-1");
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
String redirectUrl = requestCache.getRequest(request, response).getRedirectUrl();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_12
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
RequestCache requestCache = mock(RequestCache.class);
SavedRequest savedRequest = mock(SavedRequest.class);
String redirectUrl = "https://example.com/saved-request?success";
given(savedRequest.getRedirectUrl()).willReturn(redirectUrl);
given(requestCache.getRequest(any(), any())).willReturn(savedRequest);
this.filter.setRequestCache(requestCache);
authorizationRequest.setRequestURI("/saved-request");
requestCache.saveRequest(authorizationRequest, response);
- this.filter.doFilter(authorizationResponse, response, filterChain);
+ this.filter.doFilter(authorizationResponse, response, filterChain);
verify(requestCache).getRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
RequestCache requestCache = mock(RequestCache.class);
SavedRequest savedRequest = mock(SavedRequest.class);
String redirectUrl = "https://example.com/saved-request?success";
given(savedRequest.getRedirectUrl()).willReturn(redirectUrl);
given(requestCache.getRequest(any(), any())).willReturn(savedRequest);
this.filter.setRequestCache(requestCache);
authorizationRequest.setRequestURI("/saved-request");
requestCache.saveRequest(authorizationRequest, response);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(requestCache).getRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_13
Test Case Name: doFilterWhenAuthorizationSucceedsAndAnonymousAccessThenAuthorizedClientSavedToHttpSession(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), anonymousPrincipal, authorizationResponse);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsAndAnonymousAccessThenAuthorizedClientSavedToHttpSession() throws Exception {
AnonymousAuthenticationToken anonymousPrincipal = new AnonymousAuthenticationToken("key-1234", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(anonymousPrincipal);
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), anonymousPrincipal, authorizationResponse);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(anonymousPrincipal.getName());
assertThat(authorizedClient.getAccessToken()).isNotNull();
HttpSession session = authorizationResponse.getSession(false);
assertThat(session).isNotNull();
@SuppressWarnings("unchecked")
Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
assertThat(authorizedClients).isNotEmpty();
assertThat(authorizedClients).hasSize(1);
assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_177_14
Test Case Name: doFilterWhenAuthorizationSucceedsAndAnonymousAccessNullAuthenticationThenAuthorizedClientSavedToHttpSession(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationCodeGrantFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), null, authorizationResponse);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationSucceedsAndAnonymousAccessNullAuthenticationThenAuthorizedClientSavedToHttpSession() throws Exception {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), null, authorizationResponse);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo("anonymousUser");
assertThat(authorizedClient.getAccessToken()).isNotNull();
HttpSession session = authorizationResponse.getSession(false);
assertThat(session).isNotNull();
@SuppressWarnings("unchecked")
Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
assertThat(authorizedClients).isNotEmpty();
assertThat(authorizedClients).hasSize(1);
assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Mock Clone Instance #spring-security_MCI_178
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 10
- MO Count: 10
Reusable Method
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
The refactoring details in each test cases
Test Case ID #spring-security_Test_178_1
Test Case Name: doFilterWhenNotAuthorizationResponseThenNextFilter(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenNotAuthorizationResponseThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
- verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filter, never()).attemptAuthentication(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenNotAuthorizationResponseThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filter, never()).attemptAuthentication(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_2
Test Case Name: doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
// NOTE:
// A valid Authorization Response contains either a 'code' or 'error' parameter.
// Don't set it to force an invalid Authorization Response.
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_3
Test Case Name: doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("authorization_request_not_found");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("authorization_request_not_found");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_4
Test Case Name: doFilterWhenAuthorizationResponseClientRegistrationNotFoundThenClientRegistrationNotFoundError(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
// @formatter:off
ClientRegistration registrationNotFound = ClientRegistration.withRegistrationId("registration-not-found").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
// @formatter:on
this.setUpAuthorizationRequest(request, response, registrationNotFound, state);
- this.filter.doFilter(request, response, filterChain);
+ this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseClientRegistrationNotFoundThenClientRegistrationNotFoundError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
ClientRegistration registrationNotFound = ClientRegistration.withRegistrationId("registration-not-found").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
this.setUpAuthorizationRequest(request, response, registrationNotFound, state);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("client_registration_not_found");
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_5
Test Case Name: doFilterWhenAuthorizationResponseValidThenAuthorizationRequestRemoved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizationRequestRemoved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(request)).isNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizationRequestRemoved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(request)).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_6
Test Case Name: doFilterWhenAuthorizationResponseValidThenAuthorizedClientSaved(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizedClientSaved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration1, state);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(request, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), this.loginAuthentication, request);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizedClientSaved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration1, state);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(request, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registration1.getRegistrationId(), this.loginAuthentication, request);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_7
Test Case Name: doFilterWhenCustomFilterProcessesUrlThenFilterProcesses(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(this.filter).attemptAuthentication(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomFilterProcessesUrlThenFilterProcesses() throws Exception {
String filterProcessesUrl = "/login/oauth2/custom/*";
this.filter = spy(new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, this.authorizedClientRepository, filterProcessesUrl));
this.filter.setAuthenticationManager(this.authenticationManager);
String requestUri = "/login/oauth2/custom/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(this.filter).attemptAuthentication(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_8
Test Case Name: doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("http");
request.setServerName("localhost");
request.setServerPort(80);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
String expectedRedirectUri = "http://localhost/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_9
Test Case Name: doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(443);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
String expectedRedirectUri = "https://example.com/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Test Case ID #spring-security_Test_178_10
Test Case Name: doFilterWhenAuthorizationResponseHasNonDefaultPortThenRedirectUriMatchingIncludesPort(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\OAuth2LoginAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(9090);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `filterChain`
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
String expectedRedirectUri = "https://example.com:9090/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationResponseHasNonDefaultPortThenRedirectUriMatchingIncludesPort() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(9090);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
String expectedRedirectUri = "https://example.com:9090/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Reusable Method for MCI (click to expand)
private FilterChain filterChain;
@BeforeEach
public void setUp() {
filterChain = mock(FilterChain.class);
}
filterChain
Mock Clone Instance #spring-security_MCI_179
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 5
- MO Count: 5
Reusable Method
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
The refactoring details in each test cases
Test Case ID #spring-security_Test_179_1
Test Case Name: strategyFailureInvokesFailureHandler(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
authenticateUser();
SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
verify(failureHandler).onAuthenticationFailure(request, response, exception);
Original Test Code (click to expand)
@Test
public void strategyFailureInvokesFailureHandler() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
filter.setAuthenticationFailureHandler(failureHandler);
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
authenticateUser();
SessionAuthenticationException exception = new SessionAuthenticationException("Failure");
willThrow(exception).given(strategy).onAuthentication(SecurityContextHolder.getContext().getAuthentication(), request, response);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
verify(failureHandler).onAuthenticationFailure(request, response, exception);
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_179_2
Test Case Name: responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
filter.setInvalidSessionStrategy(iss);
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut");
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToTimeoutUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
SimpleRedirectInvalidSessionStrategy iss = new SimpleRedirectInvalidSessionStrategy("/timedOut");
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/timedOut");
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_179_3
Test Case Name: responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfSetAndSessionIsInvalid() throws Exception {
SecurityContextRepository repo = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy strategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(repo, strategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getRedirectedUrl()).isNull();
request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
RequestedUrlRedirectInvalidSessionStrategy iss = new RequestedUrlRedirectInvalidSessionStrategy();
iss.setCreateNewSession(true);
filter.setInvalidSessionStrategy(iss);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_179_4
Test Case Name: responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
// when
- filter.doFilter(request, response, chain);
+ filter.doFilter(request, response, fc);
// then
verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, fc);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfContextPathIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setContextRelative(true);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/context/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/context/requested");
assertThat(response.getStatus()).isEqualTo(302);
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_179_5
Test Case Name: responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\session\SessionManagementFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
// when
- filter.doFilter(request, response, chain);
+ filter.doFilter(request, response, fc);
// then
verify(securityContextRepository).containsContext(request);
- verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
+ verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, fc);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
Original Test Code (click to expand)
@Test
public void responseIsRedirectedToRequestedUrlIfStatusCodeIsSetAndSessionIsInvalid() throws Exception {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.setStatusCode(HttpStatus.TEMPORARY_REDIRECT);
RequestedUrlRedirectInvalidSessionStrategy invalidSessionStrategy = new RequestedUrlRedirectInvalidSessionStrategy();
invalidSessionStrategy.setCreateNewSession(true);
invalidSessionStrategy.setRedirectStrategy(redirectStrategy);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
SessionManagementFilter filter = new SessionManagementFilter(securityContextRepository, sessionAuthenticationStrategy);
filter.setInvalidSessionStrategy(invalidSessionStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestedSessionId("xxx");
request.setRequestedSessionIdValid(false);
request.setRequestURI("/requested");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(securityContextRepository).containsContext(request);
verifyNoMoreInteractions(securityContextRepository, sessionAuthenticationStrategy, chain);
assertThat(response.isCommitted()).isTrue();
assertThat(response.getRedirectedUrl()).isEqualTo("/requested");
assertThat(response.getStatus()).isEqualTo(307);
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Mock Clone Instance #spring-security_MCI_180
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 4
- MO Count: 4
Reusable Method
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
The refactoring details in each test cases
Test Case ID #spring-security_Test_180_1
Test Case Name: contextIsClearedAfterChainProceeds(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\SecurityContextPersistenceFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void contextIsClearedAfterChainProceeds() throws Exception {
- final FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
- filter.doFilter(request, response, chain);
+ filter.doFilter(request, response, chain);
- verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void contextIsClearedAfterChainProceeds() throws Exception {
final FilterChain chain = mock(FilterChain.class);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_180_2
Test Case Name: filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\SecurityContextPersistenceFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
- final FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(mock(SecurityContextRepository.class));
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
- filter.doFilter(request, response, chain);
+ filter.doFilter(request, response, chain);
- verify(chain).doFilter(request, response);
+ verify(chain).doFilter(request, response);
}
Original Test Code (click to expand)
@Test
public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
final FilterChain chain = mock(FilterChain.class);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(mock(SecurityContextRepository.class));
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
filter.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_180_3
Test Case Name: sessionIsEagerlyCreatedWhenConfigured(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\SecurityContextPersistenceFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
- final FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
filter.setForceEagerSessionCreation(true);
- filter.doFilter(request, response, chain);
+ filter.doFilter(request, response, chain);
assertThat(request.getSession(false)).isNotNull();
}
Original Test Code (click to expand)
@Test
public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
final FilterChain chain = mock(FilterChain.class);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
filter.setForceEagerSessionCreation(true);
filter.doFilter(request, response, chain);
assertThat(request.getSession(false)).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_180_4
Test Case Name: nullSecurityContextRepoDoesntSaveContextOrCreateSession(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\SecurityContextPersistenceFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void nullSecurityContextRepoDoesntSaveContextOrCreateSession() throws Exception {
- final FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextRepository repo = new NullSecurityContextRepository();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
filter.doFilter(request, response, chain);
assertThat(repo.containsContext(request)).isFalse();
assertThat(request.getSession(false)).isNull();
}
Original Test Code (click to expand)
@Test
public void nullSecurityContextRepoDoesntSaveContextOrCreateSession() throws Exception {
final FilterChain chain = mock(FilterChain.class);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextRepository repo = new NullSecurityContextRepository();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
filter.doFilter(request, response, chain);
assertThat(repo.containsContext(request)).isFalse();
assertThat(request.getSession(false)).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Mock Clone Instance #spring-security_MCI_181
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 6
- MO Count: 6
Reusable Method
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
The refactoring details in each test cases
Test Case ID #spring-security_Test_181_1
Test Case Name: switchToLockedAccountCausesRedirectToSwitchFailureUrl(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
filter.setUserDetailsService(new MockUserDetailsService());
filter.afterPropertiesSet();
// Check it with no url set (should get a text response)
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getErrorMessage()).isNotNull();
// Now check for the redirect
request.setContextPath("/mywebapp");
request.setRequestURI("/mywebapp/login/impersonate");
filter = new SwitchUserFilter();
filter.setTargetUrl("/target");
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchFailureUrl("/switchfailed");
filter.afterPropertiesSet();
response = new MockHttpServletResponse();
- chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed");
assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed");
Original Test Code (click to expand)
@Test
public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login/impersonate");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "mcgarrett");
MockHttpServletResponse response = new MockHttpServletResponse();
SwitchUserFilter filter = new SwitchUserFilter();
filter.setTargetUrl("/target");
filter.setUserDetailsService(new MockUserDetailsService());
filter.afterPropertiesSet();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getErrorMessage()).isNotNull();
request.setContextPath("/mywebapp");
request.setRequestURI("/mywebapp/login/impersonate");
filter = new SwitchUserFilter();
filter.setTargetUrl("/target");
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchFailureUrl("/switchfailed");
filter.afterPropertiesSet();
response = new MockHttpServletResponse();
chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed");
assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_181_2
Test Case Name: exitUserJackLordToDanoSucceeds(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
// run 'exit'
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
// check current user, should be back to original user (dano)
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
Original Test Code (click to expand)
@Test
public void exitUserJackLordToDanoSucceeds() throws Exception {
UsernamePasswordAuthenticationToken source = UsernamePasswordAuthenticationToken.authenticated("dano", "hawaii50", ROLES_12);
List<GrantedAuthority> adminAuths = new ArrayList<>();
adminAuths.addAll(ROLES_12);
adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
UsernamePasswordAuthenticationToken admin = UsernamePasswordAuthenticationToken.authenticated("jacklord", "hawaii50", adminAuths);
SecurityContextHolder.getContext().setAuthentication(admin);
MockHttpServletRequest request = createMockSwitchRequest();
request.setRequestURI("/logout/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setExitUserUrl("/logout/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
assertThat(targetAuth.getPrincipal()).isEqualTo("dano");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_181_3
Test Case Name: exitUserWithNoCurrentUserFails(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
filter.setExitUserUrl("/logout/impersonate");
// run 'exit', expect fail due to no current user
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
@@
- verify(chain, never()).doFilter(request, response);
+ verify(chain, never()).doFilter(request, response);
Original Test Code (click to expand)
@Test
public void exitUserWithNoCurrentUserFails() throws Exception {
SecurityContextHolder.clearContext();
MockHttpServletRequest request = createMockSwitchRequest();
request.setRequestURI("/logout/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setExitUserUrl("/logout/impersonate");
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verify(chain, never()).doFilter(request, response);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_181_4
Test Case Name: redirectToTargetUrlIsCorrect(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
filter.setUserDetailsService(new MockUserDetailsService());
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/webapp/someOtherUrl");
Original Test Code (click to expand)
@Test
public void redirectToTargetUrlIsCorrect() throws Exception {
MockHttpServletRequest request = createMockSwitchRequest();
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
request.setRequestURI("/webapp/login/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl"));
filter.setUserDetailsService(new MockUserDetailsService());
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/webapp/someOtherUrl");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_181_5
Test Case Name: redirectOmitsContextPathIfUseRelativeContextSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
filter.setUserDetailsService(new MockUserDetailsService());
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl");
Original Test Code (click to expand)
@Test
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = createMockSwitchRequest();
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
request.setRequestURI("/webapp/login/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/login/impersonate");
SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl");
DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy();
contextRelativeRedirector.setContextRelative(true);
switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
filter.setSuccessHandler(switchSuccessHandler);
filter.setUserDetailsService(new MockUserDetailsService());
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_181_6
Test Case Name: testSwitchRequestFromDanoToJackLord(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
// test updates user token and context
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
// check current user
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
Original Test Code (click to expand)
@Test
public void testSwitchRequestFromDanoToJackLord() throws Exception {
UsernamePasswordAuthenticationToken auth = UsernamePasswordAuthenticationToken.unauthenticated("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/webapp/login/impersonate");
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
MockHttpServletResponse response = new MockHttpServletResponse();
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
assertThat(targetAuth.getPrincipal() instanceof UserDetails).isTrue();
assertThat(((User) targetAuth.getPrincipal()).getUsername()).isEqualTo("jacklord");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Mock Clone Instance #spring-security_MCI_182
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 6
- MO Count: 6
Reusable Method
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
The refactoring details in each test cases
Test Case ID #spring-security_Test_182_1
Test Case Name: filterWhenAuthorizationManagerVerifyPassesThenNextFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
filter.doFilter(mockRequest, mockResponse, mockFilterChain);
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
- verify(mockFilterChain).doFilter(mockRequest, mockResponse);
+ verify(mockFilterChain).doFilter(mockRequest, mockResponse);
verify(strategy).getContext();
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
given(mockAuthorizationManager.check(any(Supplier.class), any(HttpServletRequest.class))).willReturn(new AuthorizationDecision(true));
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(authenticationToken));
filter.setSecurityContextHolderStrategy(strategy);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
filter.doFilter(mockRequest, mockResponse, mockFilterChain);
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verify(mockFilterChain).doFilter(mockRequest, mockResponse);
verify(strategy).getContext();
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Test Case ID #spring-security_Test_182_2
Test Case Name: filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(), eq(mockRequest));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("Access Denied");
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
- verifyNoInteractions(mockFilterChain);
+ verifyNoInteractions(mockFilterChain);
Original Test Code (click to expand)
@Test
public void filterWhenAuthorizationManagerVerifyThrowsAccessDeniedExceptionThenStopFilterChain() {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(authenticationToken);
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(), eq(mockRequest));
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("Access Denied");
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
Supplier<Authentication> authentication = authenticationCaptor.getValue();
assertThat(authentication.get()).isEqualTo(authenticationToken);
verifyNoInteractions(mockFilterChain);
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Test Case ID #spring-security_Test_182_3
Test Case Name: filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundException(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
@Test
public void filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundException() {
AuthorizationFilter filter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated());
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("An Authentication object was not found in the SecurityContext");
verifyNoInteractions(mockFilterChain);
}
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationNullThenAuthenticationCredentialsNotFoundException() {
AuthorizationFilter filter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated());
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain)).withMessage("An Authentication object was not found in the SecurityContext");
verifyNoInteractions(mockFilterChain);
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Test Case ID #spring-security_Test_182_4
Test Case Name: doFilterWhenAuthorizationEventPublisherThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
@Test
public void doFilterWhenAuthorizationEventPublisherThenUses() throws Exception {
AuthorizationFilter authorizationFilter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated());
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
SecurityContextHolder.setContext(securityContext);
AuthorizationEventPublisher eventPublisher = mock(AuthorizationEventPublisher.class);
doCallRealMethod().when(eventPublisher).publishAuthorizationEvent(any(), any(), any(AuthorizationResult.class));
authorizationFilter.setAuthorizationEventPublisher(eventPublisher);
- authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
+ authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(HttpServletRequest.class), any(AuthorizationDecision.class));
}
Original Test Code (click to expand)
@Test
public void doFilterWhenAuthorizationEventPublisherThenUses() throws Exception {
AuthorizationFilter authorizationFilter = new AuthorizationFilter(AuthenticatedAuthorizationManager.authenticated());
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
SecurityContextHolder.setContext(securityContext);
AuthorizationEventPublisher eventPublisher = mock(AuthorizationEventPublisher.class);
doCallRealMethod().when(eventPublisher).publishAuthorizationEvent(any(), any(), any(AuthorizationResult.class));
authorizationFilter.setAuthorizationEventPublisher(eventPublisher);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(eventPublisher).publishAuthorizationEvent(any(Supplier.class), any(HttpServletRequest.class), any(AuthorizationDecision.class));
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Test Case ID #spring-security_Test_182_5
Test Case Name: doFilterWhenErrorThenDoFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(authorizationManager).check(any(Supplier.class), eq(mockRequest));
Original Test Code (click to expand)
@Test
public void doFilterWhenErrorThenDoFilter() throws Exception {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
given(authorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verify(authorizationManager).check(any(Supplier.class), eq(mockRequest));
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Test Case ID #spring-security_Test_182_6
Test Case Name: doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\access\intercept\AuthorizationFilterTests.java)
Mock Object Variable Name: mockFilterChain
Suggested Diff
@@
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
- FilterChain mockFilterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `mockFilterChain`
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verifyNoInteractions(authorizationManager);
Original Test Code (click to expand)
@Test
public void doFilterWhenErrorAndShouldFilterAllDispatcherTypesFalseThenDoNotFilter() throws Exception {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
authorizationFilter.setShouldFilterAllDispatcherTypes(false);
MockHttpServletRequest mockRequest = new MockHttpServletRequest(null, "/path");
mockRequest.setDispatcherType(DispatcherType.ERROR);
mockRequest.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
authorizationFilter.doFilter(mockRequest, mockResponse, mockFilterChain);
verifyNoInteractions(authorizationManager);
}
Reusable Method for MCI (click to expand)
private FilterChain mockFilterChain;
@BeforeEach
public void setUp() {
mockFilterChain = mock(FilterChain.class);
}
mockFilterChain
Mock Clone Instance #spring-security_MCI_183
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 6
- MO Count: 6
Reusable Method
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
The refactoring details in each test cases
Test Case ID #spring-security_Test_183_1
Test Case Name: decorateWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler).onStart(any());
Original Test Code (click to expand)
@Test
void decorateWhenDefaultsThenObserves() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler).onStart(any());
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_183_2
Test Case Name: decorateWhenNoopThenDoesNotObserve(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verifyNoInteractions(handler);
Original Test Code (click to expand)
@Test
void decorateWhenNoopThenDoesNotObserve() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.NOOP;
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain);
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verifyNoInteractions(handler);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_183_3
Test Case Name: decorateFiltersWhenDefaultsThenObserves(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
Filter filter = mock(Filter.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
Original Test Code (click to expand)
@Test
void decorateFiltersWhenDefaultsThenObserves() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
verify(handler, times(2)).onStart(any());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo(filter.getClass().getSimpleName() + ".before");
assertThat(events.get(1).getName()).isEqualTo(filter.getClass().getSimpleName() + ".after");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_183_4
Test Case Name: decorateFiltersWhenDefaultsThenUsesEventName(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
Filter filter = new BasicAuthenticationFilter();
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
Original Test Code (click to expand)
@Test
void decorateFiltersWhenDefaultsThenUsesEventName() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = new BasicAuthenticationFilter();
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Event> event = ArgumentCaptor.forClass(Observation.Event.class);
verify(handler, times(2)).onEvent(event.capture(), any());
List<Observation.Event> events = event.getAllValues();
assertThat(events.get(0).getName()).isEqualTo("authentication.basic.before");
assertThat(events.get(1).getName()).isEqualTo("authentication.basic.after");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_183_5
Test Case Name: decorateFiltersWhenErrorsThenClosesObservationOnlyOnce(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\ObservationFilterChainDecoratorTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
Filter filter = mock(Filter.class);
willThrow(IllegalArgumentException.class).given(filter).doFilter(any(), any(), any());
- FilterChain decorated = decorator.decorate(chain, List.of(filter));
+ FilterChain decorated = decorator.decorate(chain, List.of(filter));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse()));
verify(handler).onScopeClosed(any());
Original Test Code (click to expand)
@Test
void decorateFiltersWhenErrorsThenClosesObservationOnlyOnce() throws Exception {
ObservationHandler<?> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
Filter filter = mock(Filter.class);
willThrow(IllegalArgumentException.class).given(filter).doFilter(any(), any(), any());
FilterChain decorated = decorator.decorate(chain, List.of(filter));
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse()));
verify(handler).onScopeClosed(any());
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_183_6
Mock Object Variable Name: chain
Suggested Diff
@@
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
Original Test Code (click to expand)
@ParameterizedTest
@MethodSource("decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag")
void decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag(Filter filter, String expectedFilterNameTag) throws Exception {
ObservationHandler<Observation.Context> handler = mock(ObservationHandler.class);
given(handler.supportsContext(any())).willReturn(true);
ObservationRegistry registry = ObservationRegistry.create();
registry.observationConfig().observationHandler(handler);
ObservationFilterChainDecorator decorator = new ObservationFilterChainDecorator(registry);
FilterChain chain = mock(FilterChain.class);
FilterChain decorated = decorator.decorate(chain, List.of(filter));
decorated.doFilter(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse());
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onScopeClosed(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue()).isEqualTo(expectedFilterNameTag);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Mock Clone Instance #spring-security_MCI_184
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 11
- MO Count: 11
Reusable Method
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
The refactoring details in each test cases
Test Case ID #spring-security_Test_184_1
Test Case Name: filterWhenDefaultsAndNoAuthenticationThenContinues(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationManager);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationManager);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_2
Test Case Name: filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_3
Test Case Name: filterWhenDefaultsAndAuthenticationSuccessThenContinues(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
Original Test Code (click to expand)
@Test
public void filterWhenDefaultsAndAuthenticationSuccessThenContinues() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_4
Test Case Name: filterWhenCustomSecurityContextHolderStrategyThenUses(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verify(strategy).setContext(any());
Original Test Code (click to expand)
@Test
public void filterWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
filter.setSecurityContextHolderStrategy(strategy);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verify(strategy).setContext(any());
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_5
Test Case Name: filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationSuccessThenContinues() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_6
Test Case Name: filterWhenDefaultsAndAuthenticationFailThenUnauthorized(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void filterWhenDefaultsAndAuthenticationFailThenUnauthorized() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_7
Test Case Name: filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndAuthenticationFailThenUnauthorized() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_8
Test Case Name: filterWhenConvertEmptyThenOk(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, new MockHttpServletResponse(), chain);
verifyNoMoreInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void filterWhenConvertEmptyThenOk() throws Exception {
given(this.authenticationConverter.convert(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
verifyNoMoreInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_9
Test Case Name: filterWhenConvertAndAuthenticationSuccessThenSuccess(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verify(this.successHandler).onAuthenticationSuccess(any(), any(), any(), eq(authentication));
verifyNoMoreInteractions(this.failureHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
Original Test Code (click to expand)
@Test
public void filterWhenConvertAndAuthenticationSuccessThenSuccess() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.successHandler).onAuthenticationSuccess(any(), any(), any(), eq(authentication));
verifyNoMoreInteractions(this.failureHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_10
Test Case Name: filterWhenConvertAndAuthenticationEmptyThenServerError(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verifyNoMoreInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
givenResolveWillReturnAuthenticationManager();
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
verifyNoMoreInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Test Case ID #spring-security_Test_184_11
Test Case Name: filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\AuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationConverter, this.authenticationManagerResolver, this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception {
given(this.requestMatcher.matches(any())).willReturn(false);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
filter.setRequestMatcher(this.requestMatcher);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyNoMoreInteractions(this.authenticationConverter, this.authenticationManagerResolver, this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain;
Mock Clone Instance #spring-security_MCI_185
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 3
- MO Count: 3
Reusable Method
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
The refactoring details in each test cases
Test Case ID #spring-security_Test_185_1
Test Case Name: detectsExpiredSessions(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
filter.setLogoutHandlers(new LogoutHandler[] { new SecurityContextLogoutHandler() });
filter.afterPropertiesSet();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
filter.doFilter(request, response, fc);
// Expect that the filter chain will not be invoked, as we redirect to expiredUrl
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/expired.jsp");
Original Test Code (click to expand)
@Test
public void detectsExpiredSessions() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
registry.getSessionInformation(session.getId()).expireNow();
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy("/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
filter.setLogoutHandlers(new LogoutHandler[] { new SecurityContextLogoutHandler() });
filter.afterPropertiesSet();
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/expired.jsp");
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_185_2
Test Case Name: returnsExpectedMessageWhenNoExpiredUrlSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getContentAsString()).isEqualTo("This session has been expired (possibly due to multiple concurrent logins being " + "attempted as the same user).");
Original Test Code (click to expand)
@Test
public void returnsExpectedMessageWhenNoExpiredUrlSet() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
registry.getSessionInformation(session.getId()).expireNow();
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getContentAsString()).isEqualTo("This session has been expired (possibly due to multiple concurrent logins being " + "attempted as the same user).");
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_185_3
Test Case Name: lastRequestTimeUpdatesCorrectly(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\concurrent\ConcurrentSessionFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
// Setup our test fixture
SessionRegistry registry = new SessionRegistryImpl();
@@
- filter.doFilter(request, response, fc);
+ filter.doFilter(request, response, fc);
verify(fc).doFilter(request, response);
assertThat(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest)).isTrue();
Original Test Code (click to expand)
@Test
public void lastRequestTimeUpdatesCorrectly() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy("/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
Thread.sleep(1000);
filter.doFilter(request, response, fc);
verify(fc).doFilter(request, response);
assertThat(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest)).isTrue();
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Mock Clone Instance #spring-security_MCI_186
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 21
- MO Count: 21
Reusable Method
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
The refactoring details in each test cases
Test Case ID #spring-security_Test_186_1
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/some_file.html");
final MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/some_file.html");
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_2
Test Case Name: testInvalidBasicAuthorizationTokenIsIgnored(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
final MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
Original Test Code (click to expand)
@Test
public void testInvalidBasicAuthorizationTokenIsIgnored() throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_3
Test Case Name: invalidBase64IsIgnored(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void invalidBase64IsIgnored() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
// The filter chain shouldn't proceed
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Original Test Code (click to expand)
@Test
public void invalidBase64IsIgnored() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_4
Test Case Name: testNormalOperation(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
Original Test Code (click to expand)
@Test
public void testNormalOperation() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_5
Test Case Name: doFilterWhenSchemeLowercaseThenCaseInsensitveMatchWorks(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
Original Test Code (click to expand)
@Test
public void doFilterWhenSchemeLowercaseThenCaseInsensitveMatchWorks() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_6
Test Case Name: doFilterWhenSchemeMixedCaseThenCaseInsensitiveMatchWorks(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void doFilterWhenSchemeMixedCaseThenCaseInsensitiveMatchWorks() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenSchemeMixedCaseThenCaseInsensitiveMatchWorks() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_7
Test Case Name: testOtherAuthorizationSchemeIsIgnored(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
request.setServletPath("/some_file.html");
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Original Test Code (click to expand)
@Test
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
request.setServletPath("/some_file.html");
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_8
Test Case Name: testSuccessLoginThenFailureLoginResultsInSessionLosingToken(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
final MockHttpServletResponse response1 = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response1, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
// NOW PERFORM FAILED AUTHENTICATION
token = "otherUser:WRONG_PASSWORD";
request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
final MockHttpServletResponse response2 = new MockHttpServletResponse();
- chain = mock(FilterChain.class);
+ // removed local mock assignment; using global field `chain`
this.filter.doFilter(request, response2, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
request.setServletPath("/some_file.html");
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
MockHttpServletResponse response = response2;
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Original Test Code (click to expand)
@Test
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
final MockHttpServletResponse response1 = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response1, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
token = "otherUser:WRONG_PASSWORD";
request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
final MockHttpServletResponse response2 = new MockHttpServletResponse();
chain = mock(FilterChain.class);
this.filter.doFilter(request, response2, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = response2;
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_9
Test Case Name: testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(this.filter.isIgnoreFailure()).isTrue();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test - the filter chain will be invoked, as we've set ignoreFailure = true
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue() throws Exception {
String token = "rod:WRONG_PASSWORD";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
this.filter = new BasicAuthenticationFilter(this.manager);
assertThat(this.filter.isIgnoreFailure()).isTrue();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_10
Test Case Name: testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
@Test
public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse() throws Exception {
String token = "rod:WRONG_PASSWORD";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
assertThat(this.filter.isIgnoreFailure()).isFalse();
final MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
- verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Original Test Code (click to expand)
@Test
public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse() throws Exception {
String token = "rod:WRONG_PASSWORD";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
assertThat(this.filter.isIgnoreFailure()).isFalse();
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_11
Test Case Name: skippedOnErrorDispatch(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
// SEC-2054
@Test
public void skippedOnErrorDispatch() throws Exception {
String token = "bad:credentials";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(200);
}
Original Test Code (click to expand)
@Test
public void skippedOnErrorDispatch() throws Exception {
String token = "bad:credentials";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(200);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_12
Test Case Name: doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
- verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü");
Original Test Code (click to expand)
@Test
public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.UTF_8)));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_13
Test Case Name: doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
- verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
Original Test Code (click to expand)
@Test
public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.ISO_8859_1)));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü");
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME)).isNotNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_14
Test Case Name: doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
- verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
Original Test Code (click to expand)
@Test
public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = UsernamePasswordAuthenticationToken.unauthenticated("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = UsernamePasswordAuthenticationToken.authenticated("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token.getBytes(StandardCharsets.UTF_8)));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_15
Mock Object Variable Name: chain
Suggested Diff
@@
final MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
Original Test Code (click to expand)
@Test
public void requestWhenEmptyBasicAuthorizationHeaderTokenThenUnauthorized() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic ");
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_16
Test Case Name: requestWhenSecurityContextRepository(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: chain
Suggested Diff
@@
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
- FilterChain chain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
Original Test Code (click to expand)
@Test
public void requestWhenSecurityContextRepository() throws Exception {
ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class);
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
this.filter.setSecurityContextRepository(securityContextRepository);
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
verify(securityContextRepository).saveContext(contextArg.capture(), eq(request), eq(response));
assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_17
Test Case Name: doFilterWhenUsernameDoesNotChangeThenAuthenticationIsNotRequired(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
@@
- verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@
- verifyNoMoreInteractions(this.manager, filterChain);
+ verifyNoMoreInteractions(this.manager, chain);
Original Test Code (click to expand)
@Test
public void doFilterWhenUsernameDoesNotChangeThenAuthenticationIsNotRequired() throws Exception {
SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext();
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated("rod", "koala", AuthorityUtils.createAuthorityList("USER"));
securityContext.setAuthentication(authentication);
securityContextHolderStrategy.setContext(securityContext);
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_18
Test Case Name: doFilterWhenUsernameChangesThenAuthenticationIsRequired(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.manager).authenticate(authenticationCaptor.capture());
@@
- verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
Authentication authenticationRequest = authenticationCaptor.getValue();
@@
- verifyNoMoreInteractions(this.manager, filterChain);
+ verifyNoMoreInteractions(this.manager, chain);
Authentication authenticationRequest = authenticationCaptor.getValue();
assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class);
Original Test Code (click to expand)
@Test
public void doFilterWhenUsernameChangesThenAuthenticationIsRequired() throws Exception {
SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext();
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated("user", "password", AuthorityUtils.createAuthorityList("USER"));
securityContext.setAuthentication(authentication);
securityContextHolderStrategy.setContext(securityContext);
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.manager).authenticate(authenticationCaptor.capture());
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
Authentication authenticationRequest = authenticationCaptor.getValue();
assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(authenticationRequest.getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_19
Test Case Name: doFilterWhenUsernameChangesAndNotUsernamePasswordAuthenticationTokenThenAuthenticationIsRequired(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.manager).authenticate(authenticationCaptor.capture());
@@
- verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
- verifyNoMoreInteractions(this.manager, filterChain);
+ verifyNoMoreInteractions(this.manager, chain);
Authentication authenticationRequest = authenticationCaptor.getValue();
assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(authenticationRequest.getName()).isEqualTo("rod");
Original Test Code (click to expand)
@Test
public void doFilterWhenUsernameChangesAndNotUsernamePasswordAuthenticationTokenThenAuthenticationIsRequired() throws Exception {
SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();
SecurityContext securityContext = securityContextHolderStrategy.createEmptyContext();
Authentication authentication = new TestingAuthenticationToken("user", "password", "USER");
securityContext.setAuthentication(authentication);
securityContextHolderStrategy.setContext(securityContext);
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.manager).authenticate(authenticationCaptor.capture());
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
Authentication authenticationRequest = authenticationCaptor.getValue();
assertThat(authenticationRequest).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(authenticationRequest.getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_20
Test Case Name: doFilterWhenCustomAuthenticationConverterThatIgnoresRequestThenIgnores(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenCustomAuthenticationConverterThatIgnoresRequestThenIgnores() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ignored");
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
- verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
+ verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
- verifyNoMoreInteractions(this.manager, filterChain);
+ verifyNoMoreInteractions(this.manager, chain);
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomAuthenticationConverterThatIgnoresRequestThenIgnores() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ignored");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
verify(this.manager, never()).authenticate(any(Authentication.class));
verify(filterChain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
verifyNoMoreInteractions(this.manager, filterChain);
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Test Case ID #spring-security_Test_186_21
Test Case Name: doFilterWhenCustomAuthenticationConverterRequestThenAuthenticate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\www\BasicAuthenticationFilterTests.java)
Mock Object Variable Name: filterChain
Suggested Diff
@@
@Test
public void doFilterWhenCustomAuthenticationConverterRequestThenAuthenticate() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ok");
- FilterChain filterChain = mock(FilterChain.class);
+ // removed local mock; replaced with global field `chain`
MockHttpServletResponse response = new MockHttpServletResponse();
- this.filter.doFilter(request, response, filterChain);
+ this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Original Test Code (click to expand)
@Test
public void doFilterWhenCustomAuthenticationConverterRequestThenAuthenticate() throws Exception {
this.filter.setAuthenticationConverter(new TestAuthenticationConverter());
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + CodecTestUtils.encodeBase64(token));
request.setServletPath("/ok");
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(200);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
Reusable Method for MCI (click to expand)
private FilterChain chain;
@BeforeEach
public void setUp() {
chain = mock(FilterChain.class);
}
chain
Mock Clone Instance #spring-security_MCI_187
- Scope: method level
- Mocked Class:
jakarta.servlet.FilterChain
- Test Case Count: 6
- MO Count: 6
Reusable Method
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
The refactoring details in each test cases
Test Case ID #spring-security_Test_187_1
Test Case Name: testOperationWhenAuthenticationExistsInContextHolder(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter didn't change our original object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(originalAuth);
- verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A");
SecurityContextHolder.getContext().setAuthentication(originalAuth);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(originalAuth);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_187_2
Test Case Name: testOperationWhenNoAuthenticationInContextHolder(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter setup with our remembered authentication object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
- verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_187_3
Test Case Name: onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth);
- verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
+ verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
Original Test Code (click to expand)
@Test
public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered)) {
@Override
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
super.onUnsuccessfulAuthentication(request, response, failed);
SecurityContextHolder.getContext().setAuthentication(failedAuth);
}
};
filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_187_4
Test Case Name: authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
// Should return after success handler is invoked, so chain should not proceed
verifyNoMoreInteractions(fc);
Original Test Code (click to expand)
@Test
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
verifyNoMoreInteractions(fc);
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_187_5
Test Case Name: securityContextRepositoryInvokedIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(securityContextRepository).saveContext(any(), eq(request), eq(response));
Original Test Code (click to expand)
@Test
public void securityContextRepositoryInvokedIfSet() throws Exception {
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSecurityContextRepository(securityContextRepository);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(securityContextRepository).saveContext(any(), eq(request), eq(response));
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Test Case ID #spring-security_Test_187_6
Test Case Name: sessionAuthenticationStrategyInvokedIfSet(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\authentication\rememberme\RememberMeAuthenticationFilterTests.java)
Mock Object Variable Name: fc
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- FilterChain fc = mock(FilterChain.class);
+ // removed local mock; replaced with global field `fc`
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(sessionAuthenticationStrategy).onAuthentication(any(), eq(request), eq(response));
Original Test Code (click to expand)
@Test
public void sessionAuthenticationStrategyInvokedIfSet() throws Exception {
SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class);
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
verify(sessionAuthenticationStrategy).onAuthentication(any(), eq(request), eq(response));
}
Reusable Method for MCI (click to expand)
private FilterChain fc;
@BeforeEach
public void setUp() {
fc = mock(FilterChain.class);
}
fc
Mock Clone Instance #spring-security_MCI_188
- Scope: method level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.saml2.provider.service.authentication.OpenSaml5AuthenticationProvider.ResponseToken, org.springframework.security.saml2.provider.service.authentication.Saml2Authentication>
- Test Case Count: 3
- MO Count: 3
Reusable Method
private Converter<ResponseToken, Saml2Authentication> authenticationConverter;
@BeforeEach
public void setUp() {
authenticationConverter = mock(Converter.class);
}
authenticationConverter;
The refactoring details in each test cases
Test Case ID #spring-security_Test_188_1
Mock Object Variable Name: authenticationConverter
Suggested Diff
@@
@Test
public void authenticateWhenResponseAuthenticationConverterConfiguredThenUses() {
- Converter<ResponseToken, Saml2Authentication> authenticationConverter = mock(Converter.class);
+ // removed local mock; replaced with global field `authenticationConverter`
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setResponseAuthenticationConverter(authenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion();
Saml2AuthenticationToken token = token(response, verifying(registration()));
provider.authenticate(token);
- verify(authenticationConverter).convert(any());
+ verify(authenticationConverter).convert(any());
}
Original Test Code (click to expand)
@Test
public void authenticateWhenResponseAuthenticationConverterConfiguredThenUses() {
Converter<ResponseToken, Saml2Authentication> authenticationConverter = mock(Converter.class);
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setResponseAuthenticationConverter(authenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion();
Saml2AuthenticationToken token = token(response, verifying(registration()));
provider.authenticate(token);
verify(authenticationConverter).convert(any());
}
Reusable Method for MCI (click to expand)
private Converter<ResponseToken, Saml2Authentication> authenticationConverter;
@BeforeEach
public void setUp() {
authenticationConverter = mock(Converter.class);
}
authenticationConverter;
Test Case ID #spring-security_Test_188_2
Test Case Name: authenticateWhenValidateResponseAfterAssertionsThenCanHaveResponseAuthenticationConverterThatDoesntNeedANameID(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\authentication\OpenSaml5AuthenticationProviderTests.java)
Mock Object Variable Name: responseAuthenticationConverter
Suggested Diff
@@
@Test
public void authenticateWhenValidateResponseAfterAssertionsThenCanHaveResponseAuthenticationConverterThatDoesntNeedANameID() {
- Converter<ResponseToken, Saml2Authentication> responseAuthenticationConverter = mock(Converter.class);
+ // removed local mock; replaced with global field `authenticationConverter`
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setValidateResponseAfterAssertions(true);
- provider.setResponseAuthenticationConverter(responseAuthenticationConverter);
+ provider.setResponseAuthenticationConverter(authenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion((r) -> r.getAssertions().get(0).setSubject(null));
Saml2AuthenticationToken token = token(response, verifying(registration()));
provider.authenticate(token);
- verify(responseAuthenticationConverter).convert(any());
+ verify(authenticationConverter).convert(any());
}
Original Test Code (click to expand)
@Test
public void authenticateWhenValidateResponseAfterAssertionsThenCanHaveResponseAuthenticationConverterThatDoesntNeedANameID() {
Converter<ResponseToken, Saml2Authentication> responseAuthenticationConverter = mock(Converter.class);
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setValidateResponseAfterAssertions(true);
provider.setResponseAuthenticationConverter(responseAuthenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion((r) -> r.getAssertions().get(0).setSubject(null));
Saml2AuthenticationToken token = token(response, verifying(registration()));
provider.authenticate(token);
verify(responseAuthenticationConverter).convert(any());
}
Reusable Method for MCI (click to expand)
private Converter<ResponseToken, Saml2Authentication> authenticationConverter;
@BeforeEach
public void setUp() {
authenticationConverter = mock(Converter.class);
}
authenticationConverter;
Test Case ID #spring-security_Test_188_3
Test Case Name: authenticateWhenValidateResponseBeforeAssertionsThenMustHaveNameID(File: C:\Java_projects\Spring\spring-security\saml2\saml2-service-provider\src\opensaml5Test\java\org\springframework\security\saml2\provider\service\authentication\OpenSaml5AuthenticationProviderTests.java)
Mock Object Variable Name: responseAuthenticationConverter
Suggested Diff
@@
@Test
public void authenticateWhenValidateResponseBeforeAssertionsThenMustHaveNameID() {
- Converter<ResponseToken, Saml2Authentication> responseAuthenticationConverter = mock(Converter.class);
+ // removed local mock; replaced with global field `authenticationConverter`
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setValidateResponseAfterAssertions(false);
- provider.setResponseAuthenticationConverter(responseAuthenticationConverter);
+ provider.setResponseAuthenticationConverter(authenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion((r) -> r.getAssertions().get(0).setSubject(null));
Saml2AuthenticationToken token = token(response, verifying(registration()));
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token));
- verifyNoInteractions(responseAuthenticationConverter);
+ verifyNoInteractions(authenticationConverter);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenValidateResponseBeforeAssertionsThenMustHaveNameID() {
Converter<ResponseToken, Saml2Authentication> responseAuthenticationConverter = mock(Converter.class);
OpenSaml5AuthenticationProvider provider = new OpenSaml5AuthenticationProvider();
provider.setValidateResponseAfterAssertions(false);
provider.setResponseAuthenticationConverter(responseAuthenticationConverter);
Response response = TestOpenSamlObjects.signedResponseWithOneAssertion((r) -> r.getAssertions().get(0).setSubject(null));
Saml2AuthenticationToken token = token(response, verifying(registration()));
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token));
verifyNoInteractions(responseAuthenticationConverter);
}
Reusable Method for MCI (click to expand)
private Converter<ResponseToken, Saml2Authentication> authenticationConverter;
@BeforeEach
public void setUp() {
authenticationConverter = mock(Converter.class);
}
authenticationConverter;
Mock Clone Instance #spring-security_MCI_189
- Scope: class level
- Mocked Class:
org.springframework.web.reactive.function.client.ClientResponse.Headers
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockClientResponseHeaders {
public static ClientResponse.Headers createMockHeaders(String wwwAuthenticateHeader) {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE)))
.willReturn(Collections.singletonList(wwwAuthenticateHeader));
return headers;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_189_1
Test Case Name: filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\reactive\function\client\ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java)
Suggested Diff
@@
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
- ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
- given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))).willReturn(Collections.singletonList(wwwAuthenticateHeader));
+ ClientResponse.Headers headers = MockClientResponseHeaders.createMockHeaders(wwwAuthenticateHeader);
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
assertThat(publisherProbe.wasSubscribed()).isTrue();
@@
Original Test Code (click to expand)
@Test
public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler() {
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())).willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))).willReturn(Collections.singletonList(wwwAuthenticateHeader));
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
assertThat(ex.getError().getDescription()).isEqualTo("The request requires higher privileges than provided by the access token.");
assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
});
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue()).containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
Reusable Method for MCI (click to expand)
public class MockClientResponseHeaders {
public static ClientResponse.Headers createMockHeaders(String wwwAuthenticateHeader) {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE)))
.willReturn(Collections.singletonList(wwwAuthenticateHeader));
return headers;
}
}
Test Case ID #spring-security_Test_189_2
Test Case Name: filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\web\reactive\function\client\ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java)
Suggested Diff
@@
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
- ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
- given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))).willReturn(Collections.singletonList(wwwAuthenticateHeader));
+ ClientResponse.Headers headers = MockClientResponseHeaders.createMockHeaders(wwwAuthenticateHeader);
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
@@
Original Test Code (click to expand)
@Test
public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)).build();
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))).willReturn(Collections.singletonList(wwwAuthenticateHeader));
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
assertThat(ex.getError().getDescription()).isEqualTo("The request requires higher privileges than provided by the access token.");
assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
});
assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
assertThat(this.attributesCaptor.getValue()).containsExactly(entry(HttpServletRequest.class.getName(), servletRequest), entry(HttpServletResponse.class.getName(), servletResponse));
}
Reusable Method for MCI (click to expand)
public class MockClientResponseHeaders {
public static ClientResponse.Headers createMockHeaders(String wwwAuthenticateHeader) {
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE)))
.willReturn(Collections.singletonList(wwwAuthenticateHeader));
return headers;
}
}
Mock Clone Instance #spring-security_MCI_190
- Scope: method level
- Mocked Class:
org.springframework.context.ApplicationContext
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static ApplicationContext createMockApplicationContext(JwtDecoder decoderBean) {
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
return context;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_190_1
Mock Object Variable Name: context
Suggested Diff
@@
JwtDecoder decoderBean = mock(JwtDecoder.class);
JwtDecoder decoder = mock(JwtDecoder.class);
- ApplicationContext context = mock(ApplicationContext.class);
- given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
+ ApplicationContext context = createMockApplicationContext(decoderBean);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
@@
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenConflictingJwtDecodersThenTheDslWiredOneTakesPrecedence() {
JwtDecoder decoderBean = mock(JwtDecoder.class);
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
}
Reusable Method for MCI (click to expand)
private static ApplicationContext createMockApplicationContext(JwtDecoder decoderBean) {
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
return context;
}
Test Case ID #spring-security_Test_190_2
Test Case Name: getJwtDecoderWhenContextHasBeanAndUserConfiguresJwkSetUriThenJwkSetUriTakesPrecedence(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\resource\OAuth2ResourceServerConfigurerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
JwtDecoder decoder = mock(JwtDecoder.class);
- ApplicationContext context = mock(ApplicationContext.class);
- given(context.getBean(JwtDecoder.class)).willReturn(decoder);
+ ApplicationContext context = createMockApplicationContext(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isNotEqualTo(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
@@
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenContextHasBeanAndUserConfiguresJwkSetUriThenJwkSetUriTakesPrecedence() {
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isNotEqualTo(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Reusable Method for MCI (click to expand)
private static ApplicationContext createMockApplicationContext(JwtDecoder decoderBean) {
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
return context;
}
Mock Clone Instance #spring-security_MCI_191
- Scope: method level
- Mocked Class:
org.springframework.context.ApplicationContext
- Test Case Count: 5
- MO Count: 5
Reusable Method
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
The refactoring details in each test cases
Test Case ID #spring-security_Test_191_1
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void getJwtDecoderWhenConfiguredWithDecoderAndJwkSetUriThenLastOneWins() {
- ApplicationContext context = mock(ApplicationContext.class);
+ // removed local mock; replaced with global field `context`
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
JwtDecoder decoder = mock(JwtDecoder.class);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenConfiguredWithDecoderAndJwkSetUriThenLastOneWins() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
JwtDecoder decoder = mock(JwtDecoder.class);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Reusable Method for MCI (click to expand)
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
Test Case ID #spring-security_Test_191_2
Test Case Name: authenticationEntryPointWhenGivenNullThenThrowsException(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\resource\OAuth2ResourceServerConfigurerTests.java)
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void authenticationEntryPointWhenGivenNullThenThrowsException() {
- ApplicationContext context = mock(ApplicationContext.class);
+ // removed local mock; replaced with global field `context`
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.authenticationEntryPoint(null));
}
Original Test Code (click to expand)
@Test
public void authenticationEntryPointWhenGivenNullThenThrowsException() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.authenticationEntryPoint(null));
}
Reusable Method for MCI (click to expand)
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
Test Case ID #spring-security_Test_191_3
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void accessDeniedHandlerWhenGivenNullThenThrowsException() {
- ApplicationContext context = mock(ApplicationContext.class);
+ // removed local mock; replaced with global field `context`
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.accessDeniedHandler(null));
}
Original Test Code (click to expand)
@Test
public void accessDeniedHandlerWhenGivenNullThenThrowsException() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.accessDeniedHandler(null));
}
Reusable Method for MCI (click to expand)
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
Test Case ID #spring-security_Test_191_4
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void getIntrospectionClientWhenConfiguredWithClientAndIntrospectionUriThenLastOneWins() {
- ApplicationContext context = mock(ApplicationContext.class);
+ // removed local mock; replaced with global field `context`
OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(context).opaqueToken();
OpaqueTokenIntrospector client = mock(OpaqueTokenIntrospector.class);
opaqueTokenConfigurer.introspectionUri(INTROSPECTION_URI);
opaqueTokenConfigurer.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
opaqueTokenConfigurer.introspector(client);
assertThat(opaqueTokenConfigurer.getIntrospector()).isEqualTo(client);
- opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(context).opaqueToken();
+ opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(context).opaqueToken();
opaqueTokenConfigurer.introspector(client);
opaqueTokenConfigurer.introspectionUri(INTROSPECTION_URI);
opaqueTokenConfigurer.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
assertThat(opaqueTokenConfigurer.getIntrospector()).isNotSameAs(client);
}
Original Test Code (click to expand)
@Test
public void getIntrospectionClientWhenConfiguredWithClientAndIntrospectionUriThenLastOneWins() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(context).opaqueToken();
OpaqueTokenIntrospector client = mock(OpaqueTokenIntrospector.class);
opaqueTokenConfigurer.introspectionUri(INTROSPECTION_URI);
opaqueTokenConfigurer.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
opaqueTokenConfigurer.introspector(client);
assertThat(opaqueTokenConfigurer.getIntrospector()).isEqualTo(client);
opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(context).opaqueToken();
opaqueTokenConfigurer.introspector(client);
opaqueTokenConfigurer.introspectionUri(INTROSPECTION_URI);
opaqueTokenConfigurer.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
assertThat(opaqueTokenConfigurer.getIntrospector()).isNotSameAs(client);
}
Reusable Method for MCI (click to expand)
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
Test Case ID #spring-security_Test_191_5
Mock Object Variable Name: context
Suggested Diff
@@
@Test
public void getAuthenticationManagerWhenConfiguredAuthenticationManagerThenTakesPrecedence() {
- ApplicationContext context = mock(ApplicationContext.class);
+ // removed local mock; replaced with global field `context`
HttpSecurityBuilder http = mock(HttpSecurityBuilder.class);
OAuth2ResourceServerConfigurer oauth2ResourceServer = new OAuth2ResourceServerConfigurer(context);
AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
oauth2ResourceServer.jwt().authenticationManager(authenticationManager).decoder(mock(JwtDecoder.class));
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
oauth2ResourceServer = new OAuth2ResourceServerConfigurer(context);
oauth2ResourceServer.opaqueToken().authenticationManager(authenticationManager).introspector(mock(OpaqueTokenIntrospector.class));
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
verify(http, never()).authenticationProvider(any(AuthenticationProvider.class));
}
Original Test Code (click to expand)
@Test
public void getAuthenticationManagerWhenConfiguredAuthenticationManagerThenTakesPrecedence() {
ApplicationContext context = mock(ApplicationContext.class);
HttpSecurityBuilder http = mock(HttpSecurityBuilder.class);
OAuth2ResourceServerConfigurer oauth2ResourceServer = new OAuth2ResourceServerConfigurer(context);
AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
oauth2ResourceServer.jwt().authenticationManager(authenticationManager).decoder(mock(JwtDecoder.class));
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
oauth2ResourceServer = new OAuth2ResourceServerConfigurer(context);
oauth2ResourceServer.opaqueToken().authenticationManager(authenticationManager).introspector(mock(OpaqueTokenIntrospector.class));
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
verify(http, never()).authenticationProvider(any(AuthenticationProvider.class));
}
Reusable Method for MCI (click to expand)
private ApplicationContext context;
@BeforeEach
public void setUp() {
context = mock(ApplicationContext.class);
}
context;
Mock Clone Instance #spring-security_MCI_192
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.AuthorityReactiveAuthorizationManager<org.springframework.security.web.server.authorization.AuthorizationContext>
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static AuthorityReactiveAuthorizationManager<AuthorizationContext> createMockAuthorityReactiveAuthorizationManager(Authentication authentication, Mono<AuthorizationDecision> decision) {
AuthorityReactiveAuthorizationManager<AuthorizationContext> mock = mock(AuthorityReactiveAuthorizationManager.class);
given(mock.check(eq(authentication), any(AuthorizationContext.class))).willReturn(decision);
return mock;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_192_1
Test Case Name: checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: delegate1
Suggested Diff
@@
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
- given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
+ this.delegate1 = createMockAuthorityReactiveAuthorizationManager(this.authentication, Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.match2, this.delegate2);
@@
Original Test Code (click to expand)
@Test
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.match2, this.delegate2);
}
Reusable Method for MCI (click to expand)
private static AuthorityReactiveAuthorizationManager<AuthorizationContext> createMockAuthorityReactiveAuthorizationManager(Authentication authentication, Mono<AuthorizationDecision> decision) {
AuthorityReactiveAuthorizationManager<AuthorizationContext> mock = mock(AuthorityReactiveAuthorizationManager.class);
given(mock.check(eq(authentication), any(AuthorizationContext.class))).willReturn(decision);
return mock;
}
Test Case ID #spring-security_Test_192_2
Test Case Name: checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\server\authorization\DelegatingReactiveAuthorizationManagerTests.java)
Mock Object Variable Name: delegate2
Suggested Diff
@@
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
- given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
+ this.delegate2 = createMockAuthorityReactiveAuthorizationManager(this.authentication, Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
Original Test Code (click to expand)
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
given(this.match1.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
given(this.match2.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
given(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class))).willReturn(Mono.just(this.decision));
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyNoMoreInteractions(this.delegate1);
}
Reusable Method for MCI (click to expand)
private static AuthorityReactiveAuthorizationManager<AuthorizationContext> createMockAuthorityReactiveAuthorizationManager(Authentication authentication, Mono<AuthorizationDecision> decision) {
AuthorityReactiveAuthorizationManager<AuthorizationContext> mock = mock(AuthorityReactiveAuthorizationManager.class);
given(mock.check(eq(authentication), any(AuthorizationContext.class))).willReturn(decision);
return mock;
}
Mock Clone Instance #spring-security_MCI_193
- Scope: class level
- Mocked Class:
org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(final java.util.List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<java.util.List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_193_1
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginAuthenticationProviderTests.java)
Mock Object Variable Name: authoritiesMapper
Suggested Diff
@@
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
- GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
- given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
+ GrantedAuthoritiesMapper authoritiesMapper = MockGrantedAuthoritiesMapper.createMockGrantedAuthoritiesMapper(mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
OAuth2User principal = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(final java.util.List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<java.util.List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
Test Case ID #spring-security_Test_193_2
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: authoritiesMapper
Suggested Diff
@@
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
- GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
- given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
+ GrantedAuthoritiesMapper authoritiesMapper = MockGrantedAuthoritiesMapper.createMockGrantedAuthoritiesMapper(mappedAuthorities);
this.manager.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
given(this.userService.loadUser(any())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.manager.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(final java.util.List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<java.util.List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
Mock Clone Instance #spring-security_MCI_194
- Scope: class level
- Mocked Class:
org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_194_1
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProviderTests.java)
Mock Object Variable Name: authoritiesMapper
Suggested Diff
@@
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
- GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
- given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
+ GrantedAuthoritiesMapper authoritiesMapper = MockGrantedAuthoritiesMapper.createMockGrantedAuthoritiesMapper(mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
this.setUpIdToken(claims);
OidcUser principal = mock(OidcUser.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
given(this.userService.loadUser(any())).willReturn(principal);
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper);
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
Test Case ID #spring-security_Test_194_2
Test Case Name: authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: authoritiesMapper
Suggested Diff
@@
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
- GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
- given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
+ GrantedAuthoritiesMapper authoritiesMapper = MockGrantedAuthoritiesMapper.createMockGrantedAuthoritiesMapper(mappedAuthorities);
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
ClientRegistration clientRegistration = this.registration.build();
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).build();
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
claims.put(IdTokenClaimNames.SUB, "rob");
claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId()));
claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
this.manager.setAuthoritiesMapper(authoritiesMapper);
Authentication result = this.manager.authenticate(authorizationCodeAuthentication).block();
assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
Reusable Method for MCI (click to expand)
public class MockGrantedAuthoritiesMapper {
public static GrantedAuthoritiesMapper createMockGrantedAuthoritiesMapper(List<GrantedAuthority> mappedAuthorities) {
GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
given(authoritiesMapper.mapAuthorities(anyCollection()))
.willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
return authoritiesMapper;
}
}
Mock Clone Instance #spring-security_MCI_195
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.jwt.JwtDecoder
- Test Case Count: 3
- MO Count: 3
Reusable Method
private JwtDecoder jwtDecoder;
@BeforeEach
public void setUp() {
jwtDecoder = mock(JwtDecoder.class);
}
jwtDecoder
The refactoring details in each test cases
Test Case ID #spring-security_Test_195_1
Test Case Name: decodeWhenUninitializedThenSupplierInitializes(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
- JwtDecoder jwtDecoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `jwtDecoder`
SupplierJwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(() -> jwtDecoder);
supplierJwtDecoder.decode("token");
- verify(jwtDecoder).decode("token");
+ verify(jwtDecoder).decode("token");
}
Original Test Code (click to expand)
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
SupplierJwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(() -> jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private JwtDecoder jwtDecoder;
@BeforeEach
public void setUp() {
jwtDecoder = mock(JwtDecoder.class);
}
jwtDecoder
Test Case ID #spring-security_Test_195_2
Test Case Name: decodeWhenInitializedThenCaches(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
@Test
public void decodeWhenInitializedThenCaches() {
- JwtDecoder jwtDecoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `jwtDecoder`
Supplier<JwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(supplier);
supplierJwtDecoder.decode("token");
supplierJwtDecoder.decode("token");
verify(supplier, times(1)).get();
- verify(jwtDecoder, times(2)).decode("token");
+ verify(jwtDecoder, times(2)).decode("token");
}
Original Test Code (click to expand)
@Test
public void decodeWhenInitializedThenCaches() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
Supplier<JwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(supplier);
supplierJwtDecoder.decode("token");
supplierJwtDecoder.decode("token");
verify(supplier, times(1)).get();
verify(jwtDecoder, times(2)).decode("token");
}
Reusable Method for MCI (click to expand)
private JwtDecoder jwtDecoder;
@BeforeEach
public void setUp() {
jwtDecoder = mock(JwtDecoder.class);
}
jwtDecoder
Test Case ID #spring-security_Test_195_3
Test Case Name: decodeWhenInitializationInitiallyFailsThenRecoverable(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-jose\src\test\java\org\springframework\security\oauth2\jwt\SupplierJwtDecoderTests.java)
Mock Object Variable Name: jwtDecoder
Suggested Diff
@@
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
- JwtDecoder jwtDecoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `jwtDecoder`
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierJwtDecoder.decode("token"));
reset(broken);
- given(broken.get()).willReturn(jwtDecoder);
+ given(broken.get()).willReturn(jwtDecoder);
supplierJwtDecoder.decode("token");
- verify(jwtDecoder).decode("token");
+ verify(jwtDecoder).decode("token");
}
Original Test Code (click to expand)
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> supplierJwtDecoder.decode("token"));
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
}
Reusable Method for MCI (click to expand)
private JwtDecoder jwtDecoder;
@BeforeEach
public void setUp() {
jwtDecoder = mock(JwtDecoder.class);
}
jwtDecoder
Mock Clone Instance #spring-security_MCI_196
- Scope: method level
- Mocked Class:
org.springframework.security.oauth2.jwt.JwtDecoder
- Test Case Count: 5
- MO Count: 5
Reusable Method
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
The refactoring details in each test cases
Test Case ID #spring-security_Test_196_1
Mock Object Variable Name: decoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenConfiguredWithDecoderAndJwkSetUriThenLastOneWins() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
- JwtDecoder decoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `decoder`
jwtConfigurer.jwkSetUri(JWK_SET_URI);
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenConfiguredWithDecoderAndJwkSetUriThenLastOneWins() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
JwtDecoder decoder = mock(JwtDecoder.class);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Reusable Method for MCI (click to expand)
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
Test Case ID #spring-security_Test_196_2
Mock Object Variable Name: decoderBean
Suggested Diff
@@
@Test
public void getJwtDecoderWhenConflictingJwtDecodersThenTheDslWiredOneTakesPrecedence() {
- JwtDecoder decoderBean = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `decoder`
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
- given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
+ given(context.getBean(JwtDecoder.class)).willReturn(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenConflictingJwtDecodersThenTheDslWiredOneTakesPrecedence() {
JwtDecoder decoderBean = mock(JwtDecoder.class);
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoderBean);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
}
Reusable Method for MCI (click to expand)
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
Test Case ID #spring-security_Test_196_3
Test Case Name: getJwtDecoderWhenContextHasBeanAndUserConfiguresJwkSetUriThenJwkSetUriTakesPrecedence(File: C:\Java_projects\Spring\spring-security\config\src\test\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\resource\OAuth2ResourceServerConfigurerTests.java)
Mock Object Variable Name: decoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenContextHasBeanAndUserConfiguresJwkSetUriThenJwkSetUriTakesPrecedence() {
- JwtDecoder decoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `decoder`
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isNotEqualTo(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenContextHasBeanAndUserConfiguresJwkSetUriThenJwkSetUriTakesPrecedence() {
JwtDecoder decoder = mock(JwtDecoder.class);
ApplicationContext context = mock(ApplicationContext.class);
given(context.getBean(JwtDecoder.class)).willReturn(decoder);
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.jwkSetUri(JWK_SET_URI);
assertThat(jwtConfigurer.getJwtDecoder()).isNotEqualTo(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isInstanceOf(NimbusJwtDecoder.class);
}
Reusable Method for MCI (click to expand)
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
Test Case ID #spring-security_Test_196_4
Mock Object Variable Name: decoderBean
Suggested Diff
@@
@Test
public void getJwtDecoderWhenTwoJwtDecoderBeansAndAnotherWiredOnDslThenDslWiredOneTakesPrecedence() {
- JwtDecoder decoderBean = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `decoder`
JwtDecoder decoder = mock(JwtDecoder.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
- context.registerBean("decoderOne", JwtDecoder.class, () -> decoderBean);
+ context.registerBean("decoderOne", JwtDecoder.class, () -> decoder);
- context.registerBean("decoderTwo", JwtDecoder.class, () -> decoderBean);
+ context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenTwoJwtDecoderBeansAndAnotherWiredOnDslThenDslWiredOneTakesPrecedence() {
JwtDecoder decoderBean = mock(JwtDecoder.class);
JwtDecoder decoder = mock(JwtDecoder.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean("decoderOne", JwtDecoder.class, () -> decoderBean);
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoderBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
jwtConfigurer.decoder(decoder);
assertThat(jwtConfigurer.getJwtDecoder()).isEqualTo(decoder);
}
Reusable Method for MCI (click to expand)
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
Test Case ID #spring-security_Test_196_5
Mock Object Variable Name: decoder
Suggested Diff
@@
@Test
public void getJwtDecoderWhenTwoJwtDecoderBeansThenThrowsException() {
- JwtDecoder decoder = mock(JwtDecoder.class);
+ // removed local mock; replaced with global field `decoder`
GenericWebApplicationContext context = new GenericWebApplicationContext();
- context.registerBean("decoderOne", JwtDecoder.class, () -> decoder);
+ context.registerBean("decoderOne", JwtDecoder.class, () -> decoder);
- context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
+ context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwtConfigurer::getJwtDecoder);
}
Original Test Code (click to expand)
@Test
public void getJwtDecoderWhenTwoJwtDecoderBeansThenThrowsException() {
JwtDecoder decoder = mock(JwtDecoder.class);
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean("decoderOne", JwtDecoder.class, () -> decoder);
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(jwtConfigurer::getJwtDecoder);
}
Reusable Method for MCI (click to expand)
private JwtDecoder decoder;
@BeforeEach
public void setUp() {
decoder = mock(JwtDecoder.class);
}
decoder;
Mock Clone Instance #spring-security_MCI_197
- Scope: class level
- Mocked Class:
org.springframework.test.web.servlet.request.RequestPostProcessor
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockRequestPostProcessor {
public static RequestPostProcessor createMockRequestPostProcessor() {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
return postProcessor;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_197_1
Test Case Name: postProcessorsAreMergedDuringMockMvcPerform(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\web\servlet\request\SecurityMockMvcRequestBuildersFormLoginTests.java)
Mock Object Variable Name: postProcessor
Suggested Diff
@@
@Test
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
- RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
- given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
+ RequestPostProcessor postProcessor = MockRequestPostProcessor.createMockRequestPostProcessor();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(formLogin()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept")).isEqualTo(MediaType.toString(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)));
assertThat(mvcResult.getRequest().getParameter("username")).isEqualTo("user");
assertThat(mvcResult.getRequest().getParameter("password")).isEqualTo("password");
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/login");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
@@
Original Test Code (click to expand)
@Test
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(formLogin()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept")).isEqualTo(MediaType.toString(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)));
assertThat(mvcResult.getRequest().getParameter("username")).isEqualTo("user");
assertThat(mvcResult.getRequest().getParameter("password")).isEqualTo("password");
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/login");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
Reusable Method for MCI (click to expand)
public class MockRequestPostProcessor {
public static RequestPostProcessor createMockRequestPostProcessor() {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
return postProcessor;
}
}
Test Case ID #spring-security_Test_197_2
Test Case Name: postProcessorsAreMergedDuringMockMvcPerform(File: C:\Java_projects\Spring\spring-security\test\src\test\java\org\springframework\security\test\web\servlet\request\SecurityMockMvcRequestBuildersFormLogoutTests.java)
Mock Object Variable Name: postProcessor
Suggested Diff
@@
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
- RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
- given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
+ RequestPostProcessor postProcessor = MockRequestPostProcessor.createMockRequestPostProcessor();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(logout()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept")).isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)));
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/logout");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
@@
Original Test Code (click to expand)
@Test
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(logout()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept")).isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)));
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/logout");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
Reusable Method for MCI (click to expand)
public class MockRequestPostProcessor {
public static RequestPostProcessor createMockRequestPostProcessor() {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
return postProcessor;
}
}
Mock Clone Instance #spring-security_MCI_198
- Scope: method level
- Mocked Class:
org.springframework.security.crypto.password.PasswordEncoder
- Test Case Count: 3
- MO Count: 3
Reusable Method
private static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder encoder = mock(PasswordEncoder.class);
given(encoder.matches(any(), any())).willReturn(matchesReturn);
return encoder;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_198_1
Test Case Name: authenticateWhenSuccessAndPasswordManagerThenUpdates(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
String password = "password";
String encodedPassword = "encoded";
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", password);
- PasswordEncoder encoder = mock(PasswordEncoder.class);
+ PasswordEncoder encoder = createMockPasswordEncoder(true);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
- given(encoder.matches(any(), any())).willReturn(true);
- given(encoder.upgradeEncoding(any())).willReturn(true);
- given(encoder.encode(any())).willReturn(encodedPassword);
+ given(encoder.upgradeEncoding(any())).willReturn(true);
+ given(encoder.encode(any())).willReturn(encodedPassword);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
verify(encoder).encode(password);
verify(passwordManager).updatePassword(eq(user), eq(encodedPassword));
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenSuccessAndPasswordManagerThenUpdates() {
String password = "password";
String encodedPassword = "encoded";
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", password);
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(true);
given(encoder.encode(any())).willReturn(encodedPassword);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
given(passwordManager.updatePassword(any(), any())).willReturn(user);
Authentication result = provider.authenticate(token);
verify(encoder).encode(password);
verify(passwordManager).updatePassword(eq(user), eq(encodedPassword));
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder encoder = mock(PasswordEncoder.class);
given(encoder.matches(any(), any())).willReturn(matchesReturn);
return encoder;
}
Test Case ID #spring-security_Test_198_2
Test Case Name: authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
- PasswordEncoder encoder = mock(PasswordEncoder.class);
+ PasswordEncoder encoder = createMockPasswordEncoder(false);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
- given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
verifyNoMoreInteractions(passwordManager);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenBadCredentialsAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
verifyNoMoreInteractions(passwordManager);
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder encoder = mock(PasswordEncoder.class);
given(encoder.matches(any(), any())).willReturn(matchesReturn);
return encoder;
}
Test Case ID #spring-security_Test_198_3
Test Case Name: authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\dao\DaoAuthenticationProviderTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
- PasswordEncoder encoder = mock(PasswordEncoder.class);
+ PasswordEncoder encoder = createMockPasswordEncoder(true);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
- given(encoder.matches(any(), any())).willReturn(true);
- given(encoder.upgradeEncoding(any())).willReturn(false);
+ given(encoder.upgradeEncoding(any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
verifyNoMoreInteractions(passwordManager);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenNotUpgradeAndPasswordManagerThenNoUpdate() {
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user", "password");
PasswordEncoder encoder = mock(PasswordEncoder.class);
UserDetailsService userDetailsService = mock(UserDetailsService.class);
UserDetailsPasswordService passwordManager = mock(UserDetailsPasswordService.class);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(userDetailsService);
provider.setUserDetailsPasswordService(passwordManager);
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(true);
given(encoder.upgradeEncoding(any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
Authentication result = provider.authenticate(token);
verifyNoMoreInteractions(passwordManager);
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder encoder = mock(PasswordEncoder.class);
given(encoder.matches(any(), any())).willReturn(matchesReturn);
return encoder;
}
Mock Clone Instance #spring-security_MCI_199
- Scope: class level
- Mocked Class:
org.springframework.security.crypto.password.PasswordEncoder
- Test Case Count: 8
- MO Count: 8
Reusable Method
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_199_1
Test Case Name: authenticateWhenPasswordEncoderAndSuccessThenSuccess(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ReactiveUserDetailsServiceAuthenticationManagerTests.java)
Mock Object Variable Name: passwordEncoder
Suggested Diff
@@
@Test
public void authenticateWhenPasswordEncoderAndSuccessThenSuccess() {
- this.manager.setPasswordEncoder(this.passwordEncoder);
- given(this.passwordEncoder.matches(any(), any())).willReturn(true);
+ this.passwordEncoder = MockPasswordEncoder.createMockPasswordEncoder(true);
+ this.manager.setPasswordEncoder(this.passwordEncoder);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username, this.password);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenPasswordEncoderAndSuccessThenSuccess() {
this.manager.setPasswordEncoder(this.passwordEncoder);
given(this.passwordEncoder.matches(any(), any())).willReturn(true);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username, this.password);
Authentication authentication = this.manager.authenticate(token).block();
assertThat(authentication).isEqualTo(authentication);
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_2
Test Case Name: authenticateWhenPasswordEncoderAndFailThenFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\ReactiveUserDetailsServiceAuthenticationManagerTests.java)
Mock Object Variable Name: passwordEncoder
Suggested Diff
@@
@Test
public void authenticateWhenPasswordEncoderAndFailThenFail() {
- this.manager.setPasswordEncoder(this.passwordEncoder);
- given(this.passwordEncoder.matches(any(), any())).willReturn(false);
+ this.passwordEncoder = MockPasswordEncoder.createMockPasswordEncoder(false);
+ this.manager.setPasswordEncoder(this.passwordEncoder);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username, this.password);
Mono<Authentication> authentication = this.manager.authenticate(token);
// @formatter:off
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
// @formatter:on
}
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenPasswordEncoderAndFailThenFail() {
this.manager.setPasswordEncoder(this.passwordEncoder);
given(this.passwordEncoder.matches(any(), any())).willReturn(false);
User user = new User(this.username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.repository.findByUsername(user.getUsername())).willReturn(Mono.just(user));
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.username, this.password);
Mono<Authentication> authentication = this.manager.authenticate(token);
StepVerifier.create(authentication).expectError(BadCredentialsException.class).verify();
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_3
Test Case Name: authenticateWhenCustomSchedulerThenUsed(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
given(this.scheduler.schedule(any())).willAnswer((a) -> {
Runnable r = a.getArgument(0);
return Schedulers.immediate().schedule(r);
});
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
- given(this.encoder.matches(any(), any())).willReturn(true);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(true);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verify(this.scheduler).schedule(any());
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenCustomSchedulerThenUsed() {
given(this.scheduler.schedule(any())).willAnswer((a) -> {
Runnable r = a.getArgument(0);
return Schedulers.immediate().schedule(r);
});
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setScheduler(this.scheduler);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verify(this.scheduler).schedule(any());
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_4
Test Case Name: authenticateWhenPasswordServiceThenUpdated(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
String encodedPassword = "encoded";
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
- given(this.encoder.matches(any(), any())).willReturn(true);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(true);
given(this.encoder.upgradeEncoding(any())).willReturn(true);
given(this.encoder.encode(any())).willReturn(encodedPassword);
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenPasswordServiceThenUpdated() {
String encodedPassword = "encoded";
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(true);
given(this.encoder.encode(any())).willReturn(encodedPassword);
given(this.userDetailsPasswordService.updatePassword(any(), any())).willReturn(Mono.just(this.user));
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verify(this.encoder).encode(this.user.getPassword());
verify(this.userDetailsPasswordService).updatePassword(eq(this.user), eq(encodedPassword));
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_5
Test Case Name: authenticateWhenPasswordServiceAndBadCredentialsThenNotUpdated(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
- given(this.encoder.matches(any(), any())).willReturn(false);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.manager.authenticate(token).block());
verifyNoMoreInteractions(this.userDetailsPasswordService);
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenPasswordServiceAndBadCredentialsThenNotUpdated() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.manager.authenticate(token).block());
verifyNoMoreInteractions(this.userDetailsPasswordService);
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_6
Test Case Name: authenticateWhenPasswordServiceAndUpgradeFalseThenNotUpdated(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
@Test
public void authenticateWhenPasswordServiceAndUpgradeFalseThenNotUpdated() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
- given(this.encoder.matches(any(), any())).willReturn(true);
- given(this.encoder.upgradeEncoding(any())).willReturn(false);
- this.manager.setPasswordEncoder(this.encoder);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(true);
+ given(this.encoder.upgradeEncoding(any())).willReturn(false);
+ this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verifyNoMoreInteractions(this.userDetailsPasswordService);
}
Original Test Code (click to expand)
@Test
public void authenticateWhenPasswordServiceAndUpgradeFalseThenNotUpdated() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
given(this.encoder.upgradeEncoding(any())).willReturn(false);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
Authentication result = this.manager.authenticate(token).block();
verifyNoMoreInteractions(this.userDetailsPasswordService);
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_7
Test Case Name: authenticateWhenPostAuthenticationChecksFail(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
willThrow(new LockedException("account is locked")).given(this.postAuthenticationChecks).check(any());
- given(this.encoder.matches(any(), any())).willReturn(true);
- this.manager.setPasswordEncoder(this.encoder);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(true);
+ this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword())).block()).withMessage("account is locked");
verify(this.postAuthenticationChecks).check(eq(this.user));
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenPostAuthenticationChecksFail() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
willThrow(new LockedException("account is locked")).given(this.postAuthenticationChecks).check(any());
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
this.manager.setPostAuthenticationChecks(this.postAuthenticationChecks);
assertThatExceptionOfType(LockedException.class).isThrownBy(() -> this.manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword())).block()).withMessage("account is locked");
verify(this.postAuthenticationChecks).check(eq(this.user));
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Test Case ID #spring-security_Test_199_8
Test Case Name: authenticateWhenPostAuthenticationChecksNotSet(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authentication\UserDetailsRepositoryReactiveAuthenticationManagerTests.java)
Mock Object Variable Name: encoder
Suggested Diff
@@
@Test
public void authenticateWhenPostAuthenticationChecksNotSet() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
- given(this.encoder.matches(any(), any())).willReturn(true);
- this.manager.setPasswordEncoder(this.encoder);
+ this.encoder = MockPasswordEncoder.createMockPasswordEncoder(true);
+ this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
this.manager.authenticate(token).block();
verifyNoMoreInteractions(this.postAuthenticationChecks);
}
@@
Original Test Code (click to expand)
@Test
public void authenticateWhenPostAuthenticationChecksNotSet() {
given(this.userDetailsService.findByUsername(any())).willReturn(Mono.just(this.user));
given(this.encoder.matches(any(), any())).willReturn(true);
this.manager.setPasswordEncoder(this.encoder);
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated(this.user, this.user.getPassword());
this.manager.authenticate(token).block();
verifyNoMoreInteractions(this.postAuthenticationChecks);
}
Reusable Method for MCI (click to expand)
public class MockPasswordEncoder {
public static PasswordEncoder createMockPasswordEncoder(boolean matchesReturn) {
PasswordEncoder passwordEncoder = Mockito.mock(PasswordEncoder.class);
given(passwordEncoder.matches(any(), any())).willReturn(matchesReturn);
return passwordEncoder;
}
}
Mock Clone Instance #spring-security_MCI_200
- Scope: method level
- Mocked Class:
org.springframework.security.crypto.password.PasswordEncoder
- Test Case Count: 4
- MO Count: 4
Reusable Method
private static PasswordEncoder createMockPasswordEncoder() {
PasswordEncoder mock = Mockito.mock(PasswordEncoder.class);
given(mock.matches(Mockito.anyString(), Mockito.anyString())).willReturn(true);
return mock;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_200_1
Test Case Name: matchesWhenBCryptThenDelegatesToBCrypt(File: C:\Java_projects\Spring\spring-security\crypto\src\test\java\org\springframework\security\crypto\password\DelegatingPasswordEncoderTests.java)
Mock Object Variable Name: bcrypt
Suggested Diff
@@
@Test
public void matchesWhenBCryptThenDelegatesToBCrypt() {
- given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
+ this.bcrypt = createMockPasswordEncoder();
assertThat(this.passwordEncoder.matches(this.rawPassword, this.bcryptEncodedPassword)).isTrue();
verify(this.bcrypt).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.noop);
}
Original Test Code (click to expand)
@Test
public void matchesWhenBCryptThenDelegatesToBCrypt() {
given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.bcryptEncodedPassword)).isTrue();
verify(this.bcrypt).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.noop);
}
@BeforeEach
public void setup() {
this.delegates = new HashMap<>();
this.delegates.put(this.bcryptId, this.bcrypt);
this.delegates.put("noop", this.noop);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
this.onlySuffixPasswordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$");
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder() {
PasswordEncoder mock = Mockito.mock(PasswordEncoder.class);
given(mock.matches(Mockito.anyString(), Mockito.anyString())).willReturn(true);
return mock;
}
Test Case ID #spring-security_Test_200_2
Test Case Name: matchesWhenBCryptBySpecifyDelegatingPasswordEncoderThenDelegatesToBCrypt(File: C:\Java_projects\Spring\spring-security\crypto\src\test\java\org\springframework\security\crypto\password\DelegatingPasswordEncoderTests.java)
Mock Object Variable Name: bcrypt
Suggested Diff
@@
@Test
public void matchesWhenBCryptBySpecifyDelegatingPasswordEncoderThenDelegatesToBCrypt() {
- given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
+ // this.bcrypt is a shared mock; consider using createMockPasswordEncoder() in test setup if possible.
assertThat(this.onlySuffixPasswordEncoder.matches(this.rawPassword, "bcrypt$" + this.encodedPassword)).isTrue();
verify(this.bcrypt).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.noop);
}
Original Test Code (click to expand)
@Test
public void matchesWhenBCryptBySpecifyDelegatingPasswordEncoderThenDelegatesToBCrypt() {
given(this.bcrypt.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.onlySuffixPasswordEncoder.matches(this.rawPassword, "bcrypt$" + this.encodedPassword)).isTrue();
verify(this.bcrypt).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.noop);
}
@BeforeEach
public void setup() {
this.delegates = new HashMap<>();
this.delegates.put(this.bcryptId, this.bcrypt);
this.delegates.put("noop", this.noop);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
this.onlySuffixPasswordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$");
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder() {
PasswordEncoder mock = Mockito.mock(PasswordEncoder.class);
given(mock.matches(Mockito.anyString(), Mockito.anyString())).willReturn(true);
return mock;
}
Test Case ID #spring-security_Test_200_3
Test Case Name: matchesWhenNoopThenDelegatesToNoop(File: C:\Java_projects\Spring\spring-security\crypto\src\test\java\org\springframework\security\crypto\password\DelegatingPasswordEncoderTests.java)
Mock Object Variable Name: noop
Suggested Diff
@@
@Test
public void matchesWhenNoopThenDelegatesToNoop() {
- given(this.noop.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
+ this.noop = createMockPasswordEncoder();
assertThat(this.passwordEncoder.matches(this.rawPassword, this.noopEncodedPassword)).isTrue();
verify(this.noop).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.bcrypt);
}
@@
Original Test Code (click to expand)
@Test
public void matchesWhenNoopThenDelegatesToNoop() {
given(this.noop.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.noopEncodedPassword)).isTrue();
verify(this.noop).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.bcrypt);
}
@BeforeEach
public void setup() {
this.delegates = new HashMap<>();
this.delegates.put(this.bcryptId, this.bcrypt);
this.delegates.put("noop", this.noop);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
this.onlySuffixPasswordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates, "", "$");
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder() {
PasswordEncoder mock = Mockito.mock(PasswordEncoder.class);
given(mock.matches(Mockito.anyString(), Mockito.anyString())).willReturn(true);
return mock;
}
Test Case ID #spring-security_Test_200_4
Test Case Name: matchesWhenNullIdThenDelegatesToInvalidId(File: C:\Java_projects\Spring\spring-security\crypto\src\test\java\org\springframework\security\crypto\password\DelegatingPasswordEncoderTests.java)
Mock Object Variable Name: invalidId
Suggested Diff
@@
this.delegates.put(null, this.invalidId);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
- given(this.invalidId.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
+ this.invalidId = createMockPasswordEncoder();
assertThat(this.passwordEncoder.matches(this.rawPassword, this.encodedPassword)).isTrue();
verify(this.invalidId).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.bcrypt, this.noop);
Original Test Code (click to expand)
@Test
public void matchesWhenNullIdThenDelegatesToInvalidId() {
this.delegates.put(null, this.invalidId);
this.passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
given(this.invalidId.matches(this.rawPassword, this.encodedPassword)).willReturn(true);
assertThat(this.passwordEncoder.matches(this.rawPassword, this.encodedPassword)).isTrue();
verify(this.invalidId).matches(this.rawPassword, this.encodedPassword);
verifyNoMoreInteractions(this.bcrypt, this.noop);
}
Reusable Method for MCI (click to expand)
private static PasswordEncoder createMockPasswordEncoder() {
PasswordEncoder mock = Mockito.mock(PasswordEncoder.class);
given(mock.matches(Mockito.anyString(), Mockito.anyString())).willReturn(true);
return mock;
}
Mock Clone Instance #spring-security_MCI_201
- Scope: method level
- Mocked Class:
org.springframework.security.authorization.ReactiveAuthorizationManager<org.aopalliance.intercept.MethodInvocation>
- Test Case Count: 6
- MO Count: 6
Reusable Method
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_201_1
Test Case Name: invokeMonoWhenMockReactiveAuthorizationManagerThenVerify(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(true)));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManager();
+ given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(true)));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenMockReactiveAuthorizationManagerThenVerify() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(true)));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block).isEqualTo("john");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_201_2
Test Case Name: invokeFluxWhenMockReactiveAuthorizationManagerThenVerify(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision((true))));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManager();
+ given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision((true))));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenMockReactiveAuthorizationManagerThenVerify() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision((true))));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::collectList).extracting(Mono::block, InstanceOfAssertFactories.list(String.class)).containsExactly("john", "bob");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_201_3
Test Case Name: invokeWhenMockReactiveAuthorizationManagerDeniedThenAccessDeniedException(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(false)));
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManager();
+ given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(false)));
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
@@
Original Test Code (click to expand)
@Test
public void invokeWhenMockReactiveAuthorizationManagerDeniedThenAccessDeniedException() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.just(new AuthorizationDecision(false)));
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_201_4
Test Case Name: invokeMonoWhenEmptyDecisionThenInvokeDefaultPostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
- ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManager();
+ given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
@@
Original Test Code (click to expand)
@Test
public void invokeMonoWhenEmptyDecisionThenInvokeDefaultPostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("mono")));
given(mockMethodInvocation.proceed()).willReturn(Mono.just("john"));
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AuthorizationDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Mono.class)).extracting(Mono::block)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_201_5
Test Case Name: invokeFluxWhenEmptyDecisionThenInvokeDefaultPostProcessor(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: mockReactiveAuthorizationManager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
- ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
- given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
- given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = createMockReactiveAuthorizationManager();
+ given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AuthorizationDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::blockFirst)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
@@
Original Test Code (click to expand)
@Test
public void invokeFluxWhenEmptyDecisionThenInvokeDefaultPostProcessor() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
given(mockMethodInvocation.proceed()).willReturn(Flux.just("john", "bob"));
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.check(any(), eq(mockMethodInvocation))).willReturn(Mono.empty());
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor interceptor = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, mockReactiveAuthorizationManager);
Object result = interceptor.invoke(mockMethodInvocation);
assertThatExceptionOfType(AuthorizationDeniedException.class).isThrownBy(() -> assertThat(result).asInstanceOf(InstanceOfAssertFactories.type(Flux.class)).extracting(Flux::blockFirst)).withMessage("Access Denied");
verify(mockReactiveAuthorizationManager).check(any(), eq(mockMethodInvocation));
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Test Case ID #spring-security_Test_201_6
Test Case Name: invokeWhenCustomAuthorizationDeniedExceptionThenThrows(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\authorization\method\AuthorizationManagerBeforeReactiveMethodInterceptorTests.java)
Mock Object Variable Name: manager
Suggested Diff
@@
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
- ReactiveAuthorizationManager<MethodInvocation> manager = mock(ReactiveAuthorizationManager.class);
- given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
- given(manager.authorize(any(), any())).willCallRealMethod();
+ ReactiveAuthorizationManager<MethodInvocation> manager = createMockReactiveAuthorizationManager();
+ given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
AuthorizationManagerBeforeReactiveMethodInterceptor advice = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> ((Mono<?>) advice.invoke(mockMethodInvocation)).block());
@@
Original Test Code (click to expand)
@Test
public void invokeWhenCustomAuthorizationDeniedExceptionThenThrows() throws Throwable {
MethodInvocation mockMethodInvocation = spy(new MockMethodInvocation(new Sample(), Sample.class.getDeclaredMethod("flux")));
ReactiveAuthorizationManager<MethodInvocation> manager = mock(ReactiveAuthorizationManager.class);
given(manager.check(any(), any())).willThrow(new MyAuthzDeniedException("denied", new AuthorizationDecision(false)));
given(manager.authorize(any(), any())).willCallRealMethod();
AuthorizationManagerBeforeReactiveMethodInterceptor advice = new AuthorizationManagerBeforeReactiveMethodInterceptor(Pointcut.TRUE, manager);
assertThatExceptionOfType(MyAuthzDeniedException.class).isThrownBy(() -> ((Mono<?>) advice.invoke(mockMethodInvocation)).block());
}
Reusable Method for MCI (click to expand)
private static ReactiveAuthorizationManager<MethodInvocation> createMockReactiveAuthorizationManager() {
ReactiveAuthorizationManager<MethodInvocation> mockReactiveAuthorizationManager = mock(ReactiveAuthorizationManager.class);
given(mockReactiveAuthorizationManager.authorize(any(), any())).willCallRealMethod();
return mockReactiveAuthorizationManager;
}
Mock Clone Instance #spring-security_MCI_202
- Scope: method level
- Mocked Class:
org.springframework.security.core.context.SecurityContextChangedListener
- Test Case Count: 5
- MO Count: 5
Reusable Method
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
The refactoring details in each test cases
Test Case ID #spring-security_Test_202_1
Test Case Name: setContextWhenInvokedThenListenersAreNotified(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: one
Suggested Diff
@@
@Test
public void setContextWhenInvokedThenListenersAreNotified() {
SecurityContextHolderStrategy delegate = spy(new MockSecurityContextHolderStrategy());
- SecurityContextChangedListener one = mock(SecurityContextChangedListener.class);
+ // removed local mock; replaced with global field `one`
SecurityContextChangedListener two = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one, two);
given(delegate.createEmptyContext()).willReturn(new SecurityContextImpl());
SecurityContext context = strategy.createEmptyContext();
strategy.setContext(context);
strategy.getContext();
- verify(one).securityContextChanged(any());
+ verify(one).securityContextChanged(any());
verify(two).securityContextChanged(any());
}
Original Test Code (click to expand)
@Test
public void setContextWhenInvokedThenListenersAreNotified() {
SecurityContextHolderStrategy delegate = spy(new MockSecurityContextHolderStrategy());
SecurityContextChangedListener one = mock(SecurityContextChangedListener.class);
SecurityContextChangedListener two = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one, two);
given(delegate.createEmptyContext()).willReturn(new SecurityContextImpl());
SecurityContext context = strategy.createEmptyContext();
strategy.setContext(context);
strategy.getContext();
verify(one).securityContextChanged(any());
verify(two).securityContextChanged(any());
}
Reusable Method for MCI (click to expand)
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
Test Case ID #spring-security_Test_202_2
Test Case Name: setContextWhenNoChangeToContextThenListenersAreNotNotified(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: listener
Suggested Diff
@@
@Test
public void setContextWhenNoChangeToContextThenListenersAreNotNotified() {
SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class);
- SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
+ // removed local mock; replaced with global field `one`
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener);
SecurityContext context = new SecurityContextImpl();
given(delegate.getContext()).willReturn(context);
strategy.setContext(strategy.getContext());
strategy.getContext();
- verifyNoInteractions(listener);
+ verifyNoInteractions(one);
}
Original Test Code (click to expand)
@Test
public void setContextWhenNoChangeToContextThenListenersAreNotNotified() {
SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class);
SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener);
SecurityContext context = new SecurityContextImpl();
given(delegate.getContext()).willReturn(context);
strategy.setContext(strategy.getContext());
strategy.getContext();
verifyNoInteractions(listener);
}
Reusable Method for MCI (click to expand)
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
Test Case ID #spring-security_Test_202_3
Test Case Name: clearContextWhenNoGetContextThenContextIsNotRead(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: listener
Suggested Diff
@@
@Test
public void clearContextWhenNoGetContextThenContextIsNotRead() {
SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class);
- SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
+ // removed local mock; replaced with global field `one`
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one);
Supplier<SecurityContext> context = mock(Supplier.class);
ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class);
given(delegate.getDeferredContext()).willReturn(context);
given(delegate.getContext()).willAnswer((invocation) -> context.get());
strategy.clearContext();
verifyNoInteractions(context);
- verify(listener).securityContextChanged(event.capture());
+ verify(one).securityContextChanged(event.capture());
assertThat(event.getValue().isCleared()).isTrue();
strategy.getContext();
verify(context).get();
strategy.clearContext();
verifyNoMoreInteractions(context);
}
Original Test Code (click to expand)
@Test
public void clearContextWhenNoGetContextThenContextIsNotRead() {
SecurityContextHolderStrategy delegate = mock(SecurityContextHolderStrategy.class);
SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener);
Supplier<SecurityContext> context = mock(Supplier.class);
ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class);
given(delegate.getDeferredContext()).willReturn(context);
given(delegate.getContext()).willAnswer((invocation) -> context.get());
strategy.clearContext();
verifyNoInteractions(context);
verify(listener).securityContextChanged(event.capture());
assertThat(event.getValue().isCleared()).isTrue();
strategy.getContext();
verify(context).get();
strategy.clearContext();
verifyNoMoreInteractions(context);
}
Reusable Method for MCI (click to expand)
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
Test Case ID #spring-security_Test_202_4
Test Case Name: getContextWhenCalledMultipleTimesThenEventPublishedOnce(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: listener
Suggested Diff
@@
@Test
public void getContextWhenCalledMultipleTimesThenEventPublishedOnce() {
SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy();
- SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
+ // removed local mock; replaced with global field `one`
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one);
strategy.setContext(new SecurityContextImpl());
- verifyNoInteractions(listener);
+ verifyNoInteractions(one);
strategy.getContext();
- verify(listener).securityContextChanged(any());
+ verify(one).securityContextChanged(any());
strategy.getContext();
- verifyNoMoreInteractions(listener);
+ verifyNoMoreInteractions(one);
}
Original Test Code (click to expand)
@Test
public void getContextWhenCalledMultipleTimesThenEventPublishedOnce() {
SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy();
SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener);
strategy.setContext(new SecurityContextImpl());
verifyNoInteractions(listener);
strategy.getContext();
verify(listener).securityContextChanged(any());
strategy.getContext();
verifyNoMoreInteractions(listener);
}
Reusable Method for MCI (click to expand)
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
Test Case ID #spring-security_Test_202_5
Test Case Name: setContextWhenCalledMultipleTimesThenPublishedEventsAlign(File: C:\Java_projects\Spring\spring-security\core\src\test\java\org\springframework\security\core\context\ListeningSecurityContextHolderStrategyTests.java)
Mock Object Variable Name: listener
Suggested Diff
@@
@Test
public void setContextWhenCalledMultipleTimesThenPublishedEventsAlign() {
SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy();
- SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
+ // removed local mock; replaced with global field `one`
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, one);
SecurityContext one = new SecurityContextImpl(new TestingAuthenticationToken("user", "pass"));
SecurityContext two = new SecurityContextImpl(new TestingAuthenticationToken("admin", "pass"));
ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class);
strategy.setContext(one);
strategy.setContext(two);
- verifyNoInteractions(listener);
+ verifyNoInteractions(one);
strategy.getContext();
- verify(listener).securityContextChanged(event.capture());
+ verify(one).securityContextChanged(event.capture());
assertThat(event.getValue().getOldContext()).isEqualTo(one);
assertThat(event.getValue().getNewContext()).isEqualTo(two);
strategy.getContext();
- verifyNoMoreInteractions(listener);
+ verifyNoMoreInteractions(one);
strategy.setContext(one);
- verifyNoMoreInteractions(listener);
+ verifyNoMoreInteractions(one);
- reset(listener);
+ reset(one);
strategy.getContext();
- verify(listener).securityContextChanged(event.capture());
+ verify(one).securityContextChanged(event.capture());
assertThat(event.getValue().getOldContext()).isEqualTo(two);
assertThat(event.getValue().getNewContext()).isEqualTo(one);
}
Original Test Code (click to expand)
@Test
public void setContextWhenCalledMultipleTimesThenPublishedEventsAlign() {
SecurityContextHolderStrategy delegate = new MockSecurityContextHolderStrategy();
SecurityContextChangedListener listener = mock(SecurityContextChangedListener.class);
SecurityContextHolderStrategy strategy = new ListeningSecurityContextHolderStrategy(delegate, listener);
SecurityContext one = new SecurityContextImpl(new TestingAuthenticationToken("user", "pass"));
SecurityContext two = new SecurityContextImpl(new TestingAuthenticationToken("admin", "pass"));
ArgumentCaptor<SecurityContextChangedEvent> event = ArgumentCaptor.forClass(SecurityContextChangedEvent.class);
strategy.setContext(one);
strategy.setContext(two);
verifyNoInteractions(listener);
strategy.getContext();
verify(listener).securityContextChanged(event.capture());
assertThat(event.getValue().getOldContext()).isEqualTo(one);
assertThat(event.getValue().getNewContext()).isEqualTo(two);
strategy.getContext();
verifyNoMoreInteractions(listener);
strategy.setContext(one);
verifyNoMoreInteractions(listener);
reset(listener);
strategy.getContext();
verify(listener).securityContextChanged(event.capture());
assertThat(event.getValue().getOldContext()).isEqualTo(two);
assertThat(event.getValue().getNewContext()).isEqualTo(one);
}
Reusable Method for MCI (click to expand)
private SecurityContextChangedListener one;
@BeforeEach
public void setUp() {
one = mock(SecurityContextChangedListener.class);
}
one
Mock Clone Instance #spring-security_MCI_203
- Scope: class level
- Mocked Class:
java.util.function.Function<org.springframework.security.oauth2.client.registration.ClientRegistration, org.springframework.security.oauth2.jose.jws.JwsAlgorithm>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockFunction {
public static Function<ClientRegistration, JwsAlgorithm> createMockFunction(ClientRegistration clientRegistration) {
Function<ClientRegistration, JwsAlgorithm> mockFunction = mock(Function.class);
given(mockFunction.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
return mockFunction;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_203_1
Test Case Name: createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customJwsAlgorithmResolver
Suggested Diff
@@
@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
- Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
ClientRegistration clientRegistration = this.registration.build();
+ Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = MockFunction.createMockFunction(clientRegistration);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
@@
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
ClientRegistration clientRegistration = this.registration.build();
given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockFunction {
public static Function<ClientRegistration, JwsAlgorithm> createMockFunction(ClientRegistration clientRegistration) {
Function<ClientRegistration, JwsAlgorithm> mockFunction = mock(Function.class);
given(mockFunction.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
return mockFunction;
}
}
Test Case ID #spring-security_Test_203_2
Test Case Name: createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\ReactiveOidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customJwsAlgorithmResolver
Suggested Diff
@@
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
- Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
ClientRegistration clientRegistration = this.registration.build();
- given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
+ ClientRegistration clientRegistration = this.registration.build();
+ Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = MockFunction.createMockFunction(clientRegistration);
+ this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomJwsAlgorithmResolverSetThenApplied() {
Function<ClientRegistration, JwsAlgorithm> customJwsAlgorithmResolver = mock(Function.class);
this.idTokenDecoderFactory.setJwsAlgorithmResolver(customJwsAlgorithmResolver);
ClientRegistration clientRegistration = this.registration.build();
given(customJwsAlgorithmResolver.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwsAlgorithmResolver).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockFunction {
public static Function<ClientRegistration, JwsAlgorithm> createMockFunction(ClientRegistration clientRegistration) {
Function<ClientRegistration, JwsAlgorithm> mockFunction = mock(Function.class);
given(mockFunction.apply(same(clientRegistration))).willReturn(MacAlgorithm.HS256);
return mockFunction;
}
}
Mock Clone Instance #spring-security_MCI_204
- Scope: class level
- Mocked Class:
java.time.Clock
- Test Case Count: 1
- MO Count: 3
Reusable Method
public class MockClock {
public static Clock createMockClock(Instant instant) {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(instant);
return clock;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_204_1
Test Case Name: authorizeWhenClockSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\JwtBearerReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: clock
Suggested Diff
@@
@Test
public void authorizeWhenClockSetThenCalled() {
- Clock clock = mock(Clock.class);
- given(clock.instant()).willReturn(Instant.now());
+ Clock clock = MockClock.createMockClock(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
verify(clock).instant();
}
Original Test Code (click to expand)
@Test
public void authorizeWhenClockSetThenCalled() {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
verify(clock).instant();
}
Reusable Method for MCI (click to expand)
public class MockClock {
public static Clock createMockClock(Instant instant) {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(instant);
return clock;
}
}
Test Case ID #spring-security_Test_204_2
Test Case Name: authorizeWhenClockSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: clock
Suggested Diff
@@
@Test
public void authorizeWhenClockSetThenCalled() {
- Clock clock = mock(Clock.class);
- given(clock.instant()).willReturn(Instant.now());
+ Clock clock = MockClock.createMockClock(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
verify(clock).instant();
}
Original Test Code (click to expand)
@Test
public void authorizeWhenClockSetThenCalled() {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
verify(clock).instant();
}
Reusable Method for MCI (click to expand)
public class MockClock {
public static Clock createMockClock(Instant instant) {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(instant);
return clock;
}
}
Test Case ID #spring-security_Test_204_3
Test Case Name: authorizeWhenClockSetThenCalled(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\TokenExchangeReactiveOAuth2AuthorizedClientProviderTests.java)
Mock Object Variable Name: clock
Suggested Diff
@@
@Test
public void authorizeWhenClockSetThenCalled() {
- Clock clock = mock(Clock.class);
- given(clock.instant()).willReturn(Instant.now());
+ Clock clock = MockClock.createMockClock(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
verify(clock).instant();
}
Original Test Code (click to expand)
@Test
public void authorizeWhenClockSetThenCalled() {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(), TestOAuth2AccessTokens.noScopes());
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient).principal(this.principal).build();
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
verify(clock).instant();
}
Reusable Method for MCI (click to expand)
public class MockClock {
public static Clock createMockClock(Instant instant) {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(instant);
return clock;
}
}
Mock Clone Instance #spring-security_MCI_205
- Scope: method level
- Mocked Class:
jakarta.servlet.http.HttpServletResponse
- Test Case Count: 3
- MO Count: 3
Reusable Method
private HttpServletResponse response;
@BeforeEach
public void setUp() {
response = mock(HttpServletResponse.class);
}
response;
The refactoring details in each test cases
Test Case ID #spring-security_Test_205_1
Test Case Name: saveTokenWhenSameSiteAndServletVersion5ThenUsesAddHeader(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\csrf\CookieCsrfTokenRepositoryTests.java)
Mock Object Variable Name: response
Suggested Diff
@@
@Test
void saveTokenWhenSameSiteAndServletVersion5ThenUsesAddHeader() {
- HttpServletResponse response = mock(HttpServletResponse.class);
+ // removed local mock; replaced with global field `response`
((MockServletContext) this.request.getServletContext()).setMajorVersion(5);
this.repository.setCookieCustomizer((builder) -> builder.sameSite("Strict"));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response, never()).addCookie(any(Cookie.class));
verify(response).addHeader(any(), any());
}
Original Test Code (click to expand)
@Test
void saveTokenWhenSameSiteAndServletVersion5ThenUsesAddHeader() {
HttpServletResponse response = mock(HttpServletResponse.class);
((MockServletContext) this.request.getServletContext()).setMajorVersion(5);
this.repository.setCookieCustomizer((builder) -> builder.sameSite("Strict"));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response, never()).addCookie(any(Cookie.class));
verify(response).addHeader(any(), any());
}
Reusable Method for MCI (click to expand)
private HttpServletResponse response;
@BeforeEach
public void setUp() {
response = mock(HttpServletResponse.class);
}
response;
Test Case ID #spring-security_Test_205_2
Test Case Name: saveTokenWhenSameSiteAndServletVersion6OrHigherThenUsesAddCookie(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\csrf\CookieCsrfTokenRepositoryTests.java)
Mock Object Variable Name: response
Suggested Diff
@@
@Test
void saveTokenWhenSameSiteAndServletVersion6OrHigherThenUsesAddCookie() {
- HttpServletResponse response = mock(HttpServletResponse.class);
+ // removed local mock; replaced with global field `response`
this.repository.setCookieCustomizer((builder) -> builder.sameSite("Strict"));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
}
Original Test Code (click to expand)
@Test
void saveTokenWhenSameSiteAndServletVersion6OrHigherThenUsesAddCookie() {
HttpServletResponse response = mock(HttpServletResponse.class);
this.repository.setCookieCustomizer((builder) -> builder.sameSite("Strict"));
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
}
Reusable Method for MCI (click to expand)
private HttpServletResponse response;
@BeforeEach
public void setUp() {
response = mock(HttpServletResponse.class);
}
response;
Test Case ID #spring-security_Test_205_3
Test Case Name: saveTokenWhenNoSameSiteThenUsesAddCookie(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\csrf\CookieCsrfTokenRepositoryTests.java)
Mock Object Variable Name: response
Suggested Diff
@@
HttpServletResponse response = mock(HttpServletResponse.class);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
((MockServletContext) this.request.getServletContext()).setMajorVersion(5);
response = mock(HttpServletResponse.class);
+ // Cannot refactor mock `response`: variable is reassigned in the test method
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
Original Test Code (click to expand)
@Test
void saveTokenWhenNoSameSiteThenUsesAddCookie() {
HttpServletResponse response = mock(HttpServletResponse.class);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
((MockServletContext) this.request.getServletContext()).setMajorVersion(5);
response = mock(HttpServletResponse.class);
this.repository.saveToken(token, this.request, response);
verify(response).addCookie(any(Cookie.class));
verify(response, never()).addHeader(any(), any());
}
Reusable Method for MCI (click to expand)
private HttpServletResponse response;
@BeforeEach
public void setUp() {
response = mock(HttpServletResponse.class);
}
response;
Mock Clone Instance #spring-security_MCI_206
- Scope: method level
- Mocked Class:
jakarta.servlet.http.HttpServletResponse
- Test Case Count: 2
- MO Count: 2
Reusable Method
private static HttpServletResponse createMockHttpServletResponse(ServletOutputStream outputstream) {
HttpServletResponse response = mock(HttpServletResponse.class);
given(response.getOutputStream()).willReturn(outputstream);
return response;
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_206_1
Test Case Name: outputStreamCloseDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\HttpSessionSecurityContextRepositoryTests.java)
Mock Object Variable Name: response
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
- HttpServletResponse response = mock(HttpServletResponse.class);
- ServletOutputStream outputstream = mock(ServletOutputStream.class);
- given(response.getOutputStream()).willReturn(outputstream);
+ ServletOutputStream outputstream = mock(ServletOutputStream.class);
+ HttpServletResponse response = createMockHttpServletResponse(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
@@
Original Test Code (click to expand)
@Test
public void outputStreamCloseDelegate() throws Exception {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
given(response.getOutputStream()).willReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().close();
verify(outputstream).close();
}
Reusable Method for MCI (click to expand)
private static HttpServletResponse createMockHttpServletResponse(ServletOutputStream outputstream) {
HttpServletResponse response = mock(HttpServletResponse.class);
given(response.getOutputStream()).willReturn(outputstream);
return response;
}
Test Case ID #spring-security_Test_206_2
Test Case Name: outputStreamFlushesDelegate(File: C:\Java_projects\Spring\spring-security\web\src\test\java\org\springframework\security\web\context\HttpSessionSecurityContextRepositoryTests.java)
Mock Object Variable Name: response
Suggested Diff
@@
MockHttpServletRequest request = new MockHttpServletRequest();
- HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
- given(response.getOutputStream()).willReturn(outputstream);
+ HttpServletResponse response = createMockHttpServletResponse(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
@@
Original Test Code (click to expand)
@Test
public void outputStreamFlushesDelegate() throws Exception {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
given(response.getOutputStream()).willReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().flush();
verify(outputstream).flush();
}
Reusable Method for MCI (click to expand)
private static HttpServletResponse createMockHttpServletResponse(ServletOutputStream outputstream) {
HttpServletResponse response = mock(HttpServletResponse.class);
given(response.getOutputStream()).willReturn(outputstream);
return response;
}
Mock Clone Instance #spring-security_MCI_207
- Scope: class level
- Mocked Class:
org.springframework.core.convert.converter.Converter<org.springframework.security.oauth2.client.endpoint.TokenExchangeGrantRequest, org.springframework.http.HttpHeaders>
- Test Case Count: 2
- MO Count: 4
Reusable Method
public class MockConverter {
public static Converter<TokenExchangeGrantRequest, HttpHeaders> createMockHeadersConverter(TokenExchangeGrantRequest grantRequest, HttpHeaders headers) {
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(grantRequest)).willReturn(headers);
return headersConverter;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_207_1
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<TokenExchangeGrantRequest, HttpHeaders> createMockHeadersConverter(TokenExchangeGrantRequest grantRequest, HttpHeaders headers) {
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(grantRequest)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_207_2
Suggested Diff
@@
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(clientRegistration, this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest);
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<TokenExchangeGrantRequest, HttpHeaders> createMockHeadersConverter(TokenExchangeGrantRequest grantRequest, HttpHeaders headers) {
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(grantRequest)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_207_3
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterAddedThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.addHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<TokenExchangeGrantRequest, HttpHeaders> createMockHeadersConverter(TokenExchangeGrantRequest grantRequest, HttpHeaders headers) {
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(grantRequest)).willReturn(headers);
return headersConverter;
}
}
Test Case ID #spring-security_Test_207_4
Suggested Diff
@@
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
- Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
+ Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = MockConverter.createMockHeadersConverter(grantRequest, headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
@@
Original Test Code (click to expand)
@Test
public void getTokenResponseWhenHeadersConverterSetThenCalled() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
TokenExchangeGrantRequest grantRequest = new TokenExchangeGrantRequest(this.clientRegistration.build(), this.subjectToken, this.actorToken);
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
HttpHeaders headers = new HttpHeaders();
headers.put("custom-header-name", Collections.singletonList("custom-header-value"));
given(headersConverter.convert(grantRequest)).willReturn(headers);
this.tokenResponseClient.setHeadersConverter(headersConverter);
this.tokenResponseClient.getTokenResponse(grantRequest).block();
verify(headersConverter).convert(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).isNull();
assertThat(recordedRequest.getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
Reusable Method for MCI (click to expand)
public class MockConverter {
public static Converter<TokenExchangeGrantRequest, HttpHeaders> createMockHeadersConverter(TokenExchangeGrantRequest grantRequest, HttpHeaders headers) {
Converter<TokenExchangeGrantRequest, HttpHeaders> headersConverter = mock();
given(headersConverter.convert(grantRequest)).willReturn(headers);
return headersConverter;
}
}
Mock Clone Instance #spring-security_MCI_208
- Scope: class level
- Mocked Class:
java.util.function.Function<org.springframework.security.oauth2.client.registration.ClientRegistration, org.springframework.security.oauth2.core.OAuth2TokenValidator<org.springframework.security.oauth2.jwt.Jwt>>
- Test Case Count: 1
- MO Count: 2
Reusable Method
public class MockFunction {
public static Function<ClientRegistration, OAuth2TokenValidator<Jwt>> createMockCustomJwtValidatorFactory(ClientRegistration clientRegistration, OAuth2TokenValidator<Jwt> validator) {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(validator);
return customJwtValidatorFactory;
}
}
The refactoring details in each test cases
Test Case ID #spring-security_Test_208_1
Test Case Name: createDecoderWhenCustomJwtValidatorFactorySetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\OidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customJwtValidatorFactory
Suggested Diff
@@
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
- Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
+ ClientRegistration clientRegistration = this.registration.build();
+ OAuth2TokenValidator<Jwt> validator = new OidcIdTokenValidator(clientRegistration);
+ Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = MockFunction.createMockCustomJwtValidatorFactory(clientRegistration, validator);
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
- ClientRegistration clientRegistration = this.registration.build();
- given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockFunction {
public static Function<ClientRegistration, OAuth2TokenValidator<Jwt>> createMockCustomJwtValidatorFactory(ClientRegistration clientRegistration, OAuth2TokenValidator<Jwt> validator) {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(validator);
return customJwtValidatorFactory;
}
}
Test Case ID #spring-security_Test_208_2
Test Case Name: createDecoderWhenCustomJwtValidatorFactorySetThenApplied(File: C:\Java_projects\Spring\spring-security\oauth2\oauth2-client\src\test\java\org\springframework\security\oauth2\client\oidc\authentication\ReactiveOidcIdTokenDecoderFactoryTests.java)
Mock Object Variable Name: customJwtValidatorFactory
Suggested Diff
@@
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
- Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
+ Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = MockFunction.createMockCustomJwtValidatorFactory(
+ this.registration.build(),
+ new OidcIdTokenValidator(this.registration.build())
+ );
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
ClientRegistration clientRegistration = this.registration.build();
- given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
@@
Original Test Code (click to expand)
@Test
public void createDecoderWhenCustomJwtValidatorFactorySetThenApplied() {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
this.idTokenDecoderFactory.setJwtValidatorFactory(customJwtValidatorFactory);
ClientRegistration clientRegistration = this.registration.build();
given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(new OidcIdTokenValidator(clientRegistration));
this.idTokenDecoderFactory.createDecoder(clientRegistration);
verify(customJwtValidatorFactory).apply(same(clientRegistration));
}
Reusable Method for MCI (click to expand)
public class MockFunction {
public static Function<ClientRegistration, OAuth2TokenValidator<Jwt>> createMockCustomJwtValidatorFactory(ClientRegistration clientRegistration, OAuth2TokenValidator<Jwt> validator) {
Function<ClientRegistration, OAuth2TokenValidator<Jwt>> customJwtValidatorFactory = mock(Function.class);
given(customJwtValidatorFactory.apply(same(clientRegistration))).willReturn(validator);
return customJwtValidatorFactory;
}
}